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

时间:2016-12-20 10:25:59

标签: mongodb mongodb-query aggregation-framework

鉴于以下文件:

static func screenshotOf(window: UIWindow) -> UIImage? {

UIGraphicsBeginImageContextWithOptions(window.bounds.size, true, UIScreen.main.scale)

        guard let currentContext = UIGraphicsGetCurrentContext() else {
            return nil
        }

        window.layer.render(in: currentContext)
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            return nil
        }

        UIGraphicsEndImageContext()
        return image
    }

我希望获得{ "_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 ] ] } 阶段得到了我想要的结果:

$unwind

是否有可能在一个流水线阶段进行制作?

1 个答案:

答案 0 :(得分:2)

distinct()也适用于数组字段,因此可以很好地完成此操作。

db.stuff.distinct('bar')

聚合框架对此过于苛刻,并且效果不佳