mongodb - How to return all documents where an array field's size is greater than a given number? -


i have document

{     "_id": objectid('56a77bfae0ce9f6a738cb2b7'),     "nameidentity": [         {             "givennameone": "latanya",             "givennamethree": "bizor",             "lastname": "bizor",             "sourcereferenceid": [                 {                     "sourcereferenceid": "56a77bfae0ce9f6a738cb2b5",                     "sourcename": "a"                 },                 {                     "sourcereferenceid": "56a77bfae0ce9f6a738cb2b5",                     "sourcename": "b"                 }             ]         }     ] } 

nameidentity array , sourcereferenceid nested array inside nameidentity. trying documents sourcereferenceid size greater 2. used aggregation :

db.entity.aggregate(    [       {          $project: {             nameidentity_count: {$size: "$nameidentity.sourcereferenceid"}          }       },       {         "$match": {             "nameidentity_count": { "$gte": 2 }          }     }    ] ) 

this not working expected, gives document 1 sourereferenceid.can tell me going wrong?

you need use dot notation , $exists operator. don't need aggregation if want find() documents "sourcereferenceid" size greater 2

db.collection.find( { "nameidentity.sourcereferenceid.2": {  "$exists": true } } ) 

but if need aggregate data then:

db.collection.aggregate([     { "$match": { "nameidentity.sourcereferenceid.2": {  "$exists": true } } }  ]) 

also have design problem because having field value 1 element array doesn't make sense. should consider change document structure looks this:

{     "_id": objectid('56a77bfae0ce9f6a738cb2b7'),     "givennameone": "latanya",     "givennamethree": "bizor",     "lastname": "bizor",     "sourcereferenceid": [         {             "sourcereferenceid": "56a77bfae0ce9f6a738cb2b5",             "sourcename": "a"         },         {             "sourcereferenceid": "56a77bfae0ce9f6a738cb2b5",             "sourcename": "b"         }     ] } 

and use following queries depending on you're trying do.

db.collection.find( { "sourcereferenceid.2": {  "$exists": true } } ) 

or

db.collection.aggregate([     { "$match": { "sourcereferenceid.2": {  "$exists": true } } }  ]) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -