bikas
bikas

Reputation: 81

MongoDB - query for a nested item inside a collection

i have a mongodb collection "result" with data like

{ "_id" : { 
           "user" : "Howard", 
           "friend" : "Sita" 
           }, 
"value" : {
          "mutualFriend" :[ "Hanks", "Bikash", "Shyam", "Bakshi" ] 
          } 
}

{ "_id" : {
          "user" : "Shiva", 
          "friend" : "Tom" 
          }, 
  "value" : { 
          "friendList" :[ "Hanks", " Tom", " Karma", " Hari", " Dinesh" ] 
            }
}

{ "_id" : { 
         "user" : "Hari", 
         "friend" : "Shiva" 
          }, 
 "value" : { 
          "mutualFriend" :[ "Tom", "Karma", "Dinesh" ] 
           } 
 }

Now, here i want to query whole Document having value.mutualFriend. how can i get the result?

Expected Output

{ "_id" : { 
           "user" : "Howard", 
           "friend" : "Sita" 
           }, 
"value" : {
          "mutualFriend" :[ "Hanks", "Bikash", "Shyam", "Bakshi" ] 
          } 
}
{ "_id" : { 
         "user" : "Hari", 
         "friend" : "Shiva" 
          }, 
 "value" : { 
          "mutualFriend" :[ "Tom", "Karma", "Dinesh" ] 
           } 
 }

i have large number of document in MongoDB collection, containing value.friendList and value.mutualFriend and then i want to find only documents with value.mutualFriend

Upvotes: 0

Views: 661

Answers (1)

Vora Ankit
Vora Ankit

Reputation: 722

db.collection.find({"value.mutualFriend.0" : { $exists : true }})

Its just make sure that the 0th element exists. you can customize your query over various array length.

Upvotes: 1

Related Questions