1
{      
    "_id" : ObjectId("5b98e5d17d542a2560ec026d"), 
    "RequestID" : "1536746958",     
    "JSON_Request" : [2,"1536746958","Heartbeat",{}],    
    "JSON_Response" : [3,"1536746958",{"currentTime":"2018-09-12T10:09:21.435Z"}] 
}

Want to fetch the documents which contains "Heartbeat" in Field "JSON_Request"

3 Answers3

0

Please try this db.getCollection('request').find({JSON_Request: 'Heartbeat'}) MongoDb 4.x

Or MongoDb 3.6 db.getCollection('request').find({ JSON_Request: { $elemMatch: {$eq: 'Heartbeat'} }}) Check elemMatch MongoDb 3.6 too

Duy Nguyen
  • 985
  • 5
  • 9
0

Try $elemMatch like so:

collection.find({ JSON_Request: { $elemMatch: { $eq: "Heartbeat" } } })
kmdreko
  • 42,554
  • 6
  • 57
  • 106
0

You can use $in operator of MongoDB. The link to the official doc: Click

Example: I have two documents in the queryAns collection as

db.queryAns.find({}).pretty()
{
    "_id" : ObjectId("5b98e5d17d542a2560ec026d"),
    "RequestID" : "1536746958",
    "JSON_Request" : [
        2,
        "1536746958",
        "Heartbeat1",
        {

        }
    ],
    "JSON_Response" : [
        3,
        "1536746958",
        {
            "currentTime" : "2018-09-12T10:09:21.435Z"
        }
    ]
}
{
    "_id" : ObjectId("5b98e5d17d542a2560ec024d"),
    "RequestID" : "1536746958",
    "JSON_Request" : [
        2,
        "1536746958",
        "Heartbeat",
        {

        }
    ],
    "JSON_Response" : [
        3,
        "1536746958",
        {
            "currentTime" : "2018-09-12T10:09:21.435Z"
        }
    ]
}

and to filter out only results which contains "Heartbeat" in the "JSON_Request",

db.queryAns.find({"JSON_Request": {$in: ["Heartbeat"]}}).pretty()

{
    "_id" : ObjectId("5b98e5d17d542a2560ec024d"),
    "RequestID" : "1536746958",
    "JSON_Request" : [
        2,
        "1536746958",
        "Heartbeat",
        {

        }
    ],
    "JSON_Response" : [
        3,
        "1536746958",
        {
            "currentTime" : "2018-09-12T10:09:21.435Z"
        }
    ]
}
Shivam Pandey
  • 3,756
  • 2
  • 19
  • 26