获取数组字段中所有唯一值的集合

2024-01-10

鉴于以下文件:

{ "_id" : ObjectId("585901b7875bab86885cf54f"), "foo" : 24, "bar" : [ 1, 2, 5, 6 ] }
{ "_id" : ObjectId("585901be875bab86885cf550"), "foo" : 42, "bar" : [ 3, 4 ] }

我想获得所有独特的价值bar字段,例如:

{"_id": "something", "bar": [1, 2, 3, 4, 5, 6]}

这是我尝试过的:

db.stuff.aggregate([{
  $group: {
    _id: null, 
    bar: {
      $addToSet: {$each: "$bar"}
    }
  }
}])

但抱怨说$each不是公认的运营商。

这确实有效:

db.stuff.aggregate([{
  $group: {
    _id: null, 
    bar: {
      $addToSet: "$bar"
    }
  }
}])

但显然会产生错误的结果:

{ "_id" : null, "bar" : [ [ 3, 4 ], [ 1, 2, 5, 6 ] ] }

EDIT

我设法通过添加第一个来获得我想要的结果$unwind stage:

db.stuff.aggregate([{
  $unwind: { "$bar" },
  $group: {
    _id: null, 
    bar: {
      $addToSet: "$bar"
    }
  }
}])

=> { "_id" : null, "bar" : [ 4, 3, 5, 2, 6, 1 ] }

是否有可能在一个管道阶段中完成它?


The distinct() https://docs.mongodb.com/manual/reference/method/db.collection.distinct/也适用于数组字段,因此可以完美地做到这一点。

db.stuff.distinct('bar')

聚合框架对此有些矫枉过正,并且性能不佳

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取数组字段中所有唯一值的集合 的相关文章

随机推荐