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

问题描述

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

{'_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,....]}
 

解决方法

您可以在$addToSet中使用$group

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内置的独特功能。

db.mycollection.distinct(“ id”)

在执行查询之前,请确保首先在字段ID之前创建索引