Many scenarios come in our programming where we need to calculate the number of the array for a Particular array. To understand the need of the query I am creating a scenario, suppose we have a collection named BLOG, and this collection contains the following fields
"Title" "Description" "CreatedDate" "Label" |
Now, suppose BLOG collection contains the following data
{ "_id" : 1, "Title" : "Title 1", "Description" : "Desc 1", "CreatedDate" : "2014-01-01T23:28:56.782Z", "Label" : ["MongoDB","Index","Array","Get Array Items"]} { "_id" : 2, "Title" : "Title 2", "Description" : "Desc 2", "CreatedDate" : "2014-01-02T20:28:56.782Z", "Label" : ["SQL Server","Merge Query"]} { "_id" : 3, "Title" : "Title 3", "Description" : "Desc 3", "CreatedDate" : "2014-01-03T08:28:56.782Z", "Label" : ["AngularJS"]} { "_id" : 4, "Title" : "Title 4", "Description" : "Desc 4", "CreatedDate" : "2014-01-04T23:28:56.782Z", "Label" : ["NodeJS","Mongoose"]} { "_id" : 5, "Title" : "Title 5", "Description" : "Desc 5", "CreatedDate" : "2014-01-05T23:28:56.782Z", "Label" : []} |
Scenario wise query
1- Suppose I want to select those records which Label is contains the 2 attribute
db.blog.find({"Label": { $size : 2 }}); Result: {"_id":2.0,"Title":"Title 2","Description":"Desc 2","CreatedDate":"2014-01-02T20:28:56.782Z","Label":["SQL Server","Merge Query"]} {"_id":4.0,"Title":"Title 4","Description":"Desc 4","CreatedDate":"2014-01-04T23:28:56.782Z","Label":["NodeJS","Mongoose"]} |
2- Apply projection means I want to select some particular fields from the document
db.blog.find({"Label": { $size : 2 }},{Title:1,_id:1});//here I want to project Title and _id Result: {"_id":2.0,"Title":"Title 2"} {"_id":4.0,"Title":"Title 4"} |
3- Document who have more than 2 records, for these type of scenario we have to apply an aggregation function
db.blog.aggregate([ { $project: { Title: 1, _id: 1, numberOfLabel: { $cond: { if : { $isArray: "$Label" }, then: { $size: "$Label" }, else : "0" } } } }, { $match: { "numberOfLabel": { $gt: 2 } } } ]); Result: {"_id":1.0,"Title":"Title 1","numberOfLabel":NumberInt(4)} |
4- Another query with the find function
db.blog.find( {Label : {$exists:true}, $where:'this.Label.length>1'},{Title:1,_id:1} ); Result: {"_id":1.0,"Title":"Title 1"} {"_id":2.0,"Title":"Title 2"} {"_id":4.0,"Title":"Title 4"} |