MongoDB projects documents with a score of more than 2

I have a collection like

{ "_id": "201503110040020021", "Line": "1", // several documents may have this Line value "LineStart": ISODate("2015-03-11T06:49:35.000Z"), "SSCEXPEND": [{ "Secuence": 10, "Title": 1, }, { "Secuence": 183, "Title": 613, }, ... ], } { "_id": "201503110040020022", "Line": "1", // several documents may have this Line value "LineStart": ISODate("2015-03-11T06:49:35.000Z"), "SSCEXPEND": [{ "Secuence": 10, "Title": 1, }, ], } 

SSCEXPEND is an array. I am trying to calculate the size of an SSC array and a project if the number is greater than or equal to 2. My query is like this

 db.entity.aggregate( [ { $project: { SSCEXPEND_count: {$size: "$SSCEXPEND"} } }, { $match: { "SSCEXPEND_count2": {$gte: ["$SSCEXPEND_count",2]} } } ] ) 

I expect the output to be only the first document whose array size is greater than 2.

Part of the project is working fine, and I can get the calculations, but I only need to project those that have an account greater than or equal to two, but my part of the match does not work. Can someone lead me like I'm wrong?

+6
source share
2 answers

You need to project other fields, and the $match pipeline should simply execute a request for a newly created field to filter documents based on the size of the array. Something like the following should work:

 db.entity.aggregate([ { "$project": { "Line": 1, "LineStart": 1, "SSCEXPEND": 1, "SSCEXPEND_count": { "$size": "$SSCEXPEND" } } }, { "$match": { "SSCEXPEND_count": { "$gte": 2 } } } ]) 

Output result :

 /* 0 */ { "result" : [ { "_id" : "201503110040020021", "Line" : "1", "LineStart" : ISODate("2015-03-11T06:49:35.000Z"), "SSCEXPEND" : [ { "Secuence" : 10, "Title" : 1 }, { "Secuence" : 183, "Title" : 613 } ], "SSCEXPEND_count" : 2 } ], "ok" : 1 } 
+5
source

This is actually a very simple query, in which the trick is to use the "dot notation" property to validate the array. All you really need to request are documents in which the array index is $exists 2 $exists , which means the array must contain elements of 3 or more:

 db.entity.find({ "SSCEXPEND.2": { "$exists": true } }) 

This is the fastest way to do this and even use indexes. There is no need for calculations in aggregation operations.

+3
source

All Articles