MongoDB投影数量大于2的文档

编程入门 行业动态 更新时间:2024-10-20 09:33:23
本文介绍了MongoDB投影数量大于2的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类似

{ "_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的文档

本文发布于:2023-11-23 20:48:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622818.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数量   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!