聚合将多个数组$ lookup展开为多个投影字段

时间:2017-12-07 13:00:45

标签: mongodb aggregation-framework

这是我目前的查询:

Follow.aggregate([
  {
    $match: {
      "user": Types.ObjectId(user_id) 
    }
  },
  {
    $unwind: "$following"
  },
  {
    $lookup: {
      "from": "users",
      "localField": "following",
      "foreignField": "createdById",
      "as": "followingUsers"
    }
  }, {
    $project: {
        "user": 1,
        "followingUsers": 1
    }
  }
])

此查询在如下文档上运行:

{
    "_id" : ObjectId("5a271a93a19d690b25a3e181"),
    "user" : ObjectId("5a271a4f50261a3c1695a391"),
    "following" : [
        ObjectId("5a257c87086eb00712fd02ec"),
        ObjectId("5a257a79086eb00712fd02eb")
    ],
    "followers" : [
        ObjectId("5a257a79086eb00712fd02eb")
    ]
}

并给出这样的结果:

{
    "_id" : ObjectId("5a271a93a19d690b25a3e181"),
    "user" : ObjectId("5a271a4f50261a3c1695a391"),
    "followingUsers" : [
        {
            "_id" : ObjectId("5a257a79086eb00712fd02eb"),
            "email" : "email@gmail.com",
            "username" : "username",
            "email_verified" : true,
            "created" : ISODate("2010-12-04T16:40:25.670Z"),
            "__v" : 0,
            "last_login" : ISODate("2010-12-06T21:14:25.538Z"),
            "is_active" : false
        }
    ]
}

上面只展开其中一个数组并跟进查找。

我想,在一个独家新闻中(假设可能)

  • 展开$following$followers数组字段
  • $lookup两个数组字段独立
  • 然后出现as,比如,followingUsersfollowersUsers

最终得到这样的结论:

{
    "_id" : ObjectId("5a271a93a19d690b25a3e181"),
    "user" : ObjectId("5a271a4f50261a3c1695a391"),
    "followingUsers" : [
        {
          "_id" : ObjectId("5a257a79086eb00712fd02eb"),
          ....
        }
    ],
    "followersUsers": [
        { 
          "_id" : ObjectId("5a257a79086eb00712fd02eb"),
          ....
        }
    ]
}

我甚至可以在MongoDB中想象这样的事情吗?

0 个答案:

没有答案