检索包含数组中不同元素的文档

时间:2016-10-19 17:51:41

标签: mongodb mongoose

我有像

这样的文件
[{"_id" : "12","name" : "test1", "nesArray" : [1,2], "createdAt" : ISODate("2016-10-15T06:17:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,3], "createdAt" :ISODate("2016-10-15T06:17:54.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,4], "createdAt" :ISODate("2016-10-15T06:17:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,2], "createdAt" :ISODate("2016-10-15T06:18:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,3], "createdAt" :ISODate("2016-10-15T06:18:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,2],"createdAt" :ISODate("2016-10-15T06:19:53.946Z") } ]

我想只检索那些有

的文档
  1. Distinct nesArray
  2. 仅限最新文件
  3. 结果应该是

       [{"_id" : "12","name" : "test1", "nesArray" : [1,4], "createdAt" :ISODate("2016-10-15T06:17:53.946Z") },
        {"_id" : "12","name" : "test1", "nesArray" : [1,3], "createdAt" :ISODate("2016-10-15T06:18:53.946Z") },
        {"_id" : "12","name" : "test1", "nesArray" : [1,2],"createdAt" :ISODate("2016-10-15T06:19:53.946Z") }]
    

    我尝试使用聚合但我不想使用聚合(Mongoose populate不能用于聚合)。

1 个答案:

答案 0 :(得分:0)

这基本上就是你尝试过的,但是使用$last获取所有字段并在之后投影具有与DB中相同的结构:

db.coll.aggregate(
  { 
    $sort: { createdAt: 1 }
  }, 
  {
    $group: {
      _id: "$nesArray", 
      id: { $last: "$_id" }, 
      name: {$last: "$name"}, 
      createdAt: { $last: "$createdAt"}
    }
  },
  {
    $project: {
      _id: "$id",
      nesArray: "$_id",
      name: 1,
      createdAt: 1
    }
  }
)