0

I am working on mongoldb database, I am actually quite new to this database, I have a collection of contacts and I want to get individual data through mongo query.

Contacts Collection

[{
"_id": "57cd2f6c3966037787ce9550",
"contact": [{
    "id": "457899979",
    "fullname": "Abcd Hello",
    "phonenumber": "123575784565",
    "currentUserid": "123456789"
}, {
    "id": "7994949849",
    "fullname": "Keyboard Mouse",
    "phonenumber": "23658974262",
    "currentUserid": "123456789"
}, {
    "id": "7848848885",
    "fullname": "Test Xyz",
    "phonenumber": "87556699632",
    "currentUserid": "123456789"
}]

}, {
"_id": "57cd2fe02c40b97791b39fe3",
"contact": [{
    "id": "457899979",
    "fullname": "iPad",
    "phonenumber": "85632889714",
    "currentUserid": "789456123"
}, {
    "id": "7994949849",
    "fullname": "Cool",
    "phonenumber": "33698777523",
    "currentUserid": "789456123"
 }]
}]

Mongo Query

db.friendslist.find({"currentUserid" : "789456123"})

But this query fetching empty results, I want to fetch the list of contacts of currentUserid : 789456123.

Please kindly go through my post and suggest me some solution.

Found Solution

db.friendslist.find({ "contact": { "$elemMatch": { "currentUserid" : "789456123"  } } }).pretty()
deeptimancode
  • 1,139
  • 4
  • 18
  • 40

1 Answers1

0

@Deeptiman, you mentioned your answer, but question id and answer id are not same.

enter image description here
this may help you to find "currentUserid": "789456123"
.in below query $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. and .pretty() used to format your code.

db.friendslist.find({
 "contact": { 
    "$elemMatch": { 
         "currentUserid" : "789456123" 
                   } 
            } 
}).pretty()
yash
  • 2,101
  • 2
  • 23
  • 32
  • thanks for your reply, no it's working absolutely fine, you can see the JSON you will find { "currentUserid" : "123456789" } – deeptimancode Sep 05 '16 at 11:53
  • can you please help me on this logic, http://stackoverflow.com/questions/39330374/how-to-find-match-elements-in-between-two-collections-in-mongodb – deeptimancode Sep 05 '16 at 12:14