我有一个类似
{ "_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是一个数组.我正在尝试计算SSC数组和项目的大小(如果计数大于或等于2).我的查询是这样的
SSCEXPEND is an array. I am trying to count the size of SSC array and project if the count is greater than or equal to 2. My query is something like this
db.entity.aggregate( [ { $project: { SSCEXPEND_count: {$size: "$SSCEXPEND"} } }, { $match: { "SSCEXPEND_count2": {$gte: ["$SSCEXPEND_count",2]} } } ] )我希望输出仅是数组大小大于2的第一个文档.
I am expecting the output to be only the the first document whose array size is greater than 2.
项目部分工作正常,我能够获得计数,但是我只需要投影那些计数大于或等于2但我的匹配部分无效的项目.谁能指导我哪里出问题了?
Project part is working fine and I am able to get the counts but I need to project only those which has count greater than or equal to two but my match part is not working. Can any one guide me as where am I going wrong?
推荐答案您需要投影其他字段和 $match 管道只需要对新创建的字段进行查询,以基于数组过滤文档尺寸.像下面这样的东西应该起作用:
You need to project the other fields and your $match pipeline will just need to do a query on the newly-created field to filter the documents based on the array size. 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 } } } ])示例输出:
/* 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 }更多推荐
MongoDB投影数量大于2的文档
发布评论