0

I have following data in mongodb collection

{
    "_id" : ObjectId("5e09ad518f49801c3275cc54"),
    "user_id" : "100",
    "user_type" : "Demo",
    "created_date" : ISODate("2019-12-30T07:54:57.885Z"),
    "updated_date" : ISODate("2019-12-30T07:54:57.885Z"),
    "communications" : [ 
        {
            "_id" : ObjectId("5e09ad558f49801c3275cc55"),
            "import_date" : ISODate("2019-12-30T07:54:57.885Z"),
            "service_provider" : "gmail",
            "communication":[],
        }, 
        {
            "_id" : ObjectId("5e09ad7f8f49801c3275cc57"),
            "import_date" : ISODate("2019-12-30T07:55:36.906Z"),
            "service_provider" : "outlook",
            "communication":[],
        }
    ],
    "__v" : 1
}

I want to find only specific communications node like gmail or outlook . I tried following query but I am getting both elements from the array

db.getCollection('emails').findOne({user_id:'100','communications.service_provider':'gmail'})

help me on this. thanks in advance

1 Answers1

0

You'll have to use elemMatch because you are searching in an array. Try this

db.getCollection('emails').findOne({
                                        user_id:'100',
                                        communications: { 
                                            $elemMatch: { service_provider: { $eq:'gmail' } }
                                        }
                                    })
Mr.Gandhi
  • 1,328
  • 8
  • 14