mongodb如何取出指定键值对的值

前端之家收集整理的这篇文章主要介绍了mongodb如何取出指定键值对的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

player表结构大致如此,且数据量级在百万:

{
	"_id”: 1,"level”: 3,"name”: "xiaoming”
}

我的需求是:快速取出所有表中的_id,并组成一个array,类似 [1,2,3,4,5,6]

db.getCollection("player").find({{},{"_id": 1}).toArray()

 这样查找出来的结果是 [{"_id": 1},{"_id": 2},{"_id": 3},{"_id": 4},{"_id": 5},{"_id": 6}]

解决方法使用聚合查询

db.getCollection("player").aggregate({$group:{_id:"hello",arr:{$push:"$_id"}}})

输出结果为:

{ ”_id” : ”hello”, ”arr” : [ 1,3] }

原文:https://cnodejs.org/topic/5763a8a56ba06f2a22f8ebff

猜你在找的MongoDB相关文章