MongoDB聚合项目返回

编程入门 行业动态 更新时间:2024-10-24 20:20:59
本文介绍了MongoDB聚合项目返回_id数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们知道是否要获取_id数组,我们可以这样做:

As we know if we want to get an array of _id we can do:

db.collections.distinct("_id");

我的问题是,如果我需要对聚合进行复杂的逻辑运算,该如何获取_id数组. 例如:

My question is how can I get an array of _id if I need to do a complicate logic with aggregate. Ex:

db.getCollection('users').aggregate({ $match : { is_register_completed : { $ne : true} } } //other operator like $lookup, $group , { $project : {_id:1} } )

我知道

{ "_id" : "1", "_id" : "2" }

我想要的就像我们做的独特

what i want is just like we do distinct

{[1,2]}

已更新: 这就是我尝试使用$ group

Updated: this is what i try to do with $group

db.getCollection('users').aggregate({ $match : { is_register_completed : { $ne : true} } }, { $group: { _id:null, all:{$addToSet: "$_id"} } }, {$project: {_id:0,all:1}} )

但我仍然得到

{ all : ["1","2"] }

或者我可以在获得

{ "_id" : "1", "_id" : "2" }

,但是地图是客户端转换,我认为这会影响性能.

, but the map is client side transformation which I think it will affect the performance.

推荐答案

引用自:如何通过mongodb聚合返回字符串数组

.aggregate()方法始终返回对象,无论您做什么 并不能改变.

The .aggregate() method always returns Objects no matter what you do and that cannot change.

原始答案: 尝试使用聚合框架:

Original Answer: Try the aggregation framework:

db.myCol.aggregate([ { $group:{_id:null, array:{$push:"$_id"}} }, { $project:{array:true,_id:false} } ])

更多推荐

MongoDB聚合项目返回

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

发布评论

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

>www.elefans.com

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