Mongodb,获取字段的不同值并将值输出为单个文档

Mongodb, get distinct values of a field and output the values as single document

我有大量具有以下结构的文档

{'_id':ObjectId(something),...., 'id':1}
{'_id':ObjectId(something),....,'id':2}
....

我想获取不同的 ID(即 'id' 字段中的值)。下面的代码可以一定程度上解决我的问题,

db.mycollection.aggregate([{$group: {_id: '$id'},{ "$out": "exist_indexes" }],{allowDiskUse: true});

但是,在输出集合 exist_indexes 中,不同的值存储为 多个文档 。像

{'_id': 1}
{'_id': 2}
....

如何在输出集合中将不同的值输出为 a single document?像这样

{"_id": [1,2,3,....]}
 

您可以在 $group

中使用 $addToSet
db.mycollection.aggregate([
  {
    $group: {
      _id: null,
      ids: { $addToSet: "$id" } // change field name ids to as you want
    }
  },
  { $project: { _id: "$ids" } }, // you can skip this if you don't want to change field name
  { $out: "exist_indexes" }
])

Playground

议程是为了获得不同的价值,那么为什么还要在输出中考虑 _id。使用 MongoDB inbuild distinct 函数。

db.mycollection.distinct("id")

确保在执行查询之前首先创建字段 id 的索引