mongodb聚集查询返回集合中的每个项目

时间:2018-07-02 14:17:14

标签: mongodb

我想使用mongodb聚合查找两个集合,这是我的查询:

db.getCollection('buddies').aggregate([
{
     $lookup:
       {
         from: "users",
         localField: "ObjectId(userId)",
         foreignField: "ObjectId(_id)",
         as: "user_buddy"
       }
  }
])

问题是我使用userId进行聚合。 usersbuddies的集合是 1比1

我希望它将添加由buddies.userId和users._id匹配的user_buddy属性,但是我得到的是不同的:

/* 1 */
{
    "_id" : ObjectId("5b3a2fca0fe843093879b5bc"),
    "isVerified" : false,
    "isActivated" : false,
    "createdAt" : ISODate("2018-07-02T13:59:05.273Z"),
    "userId" : "5b2deca18966a405412d1266",
    "phone" : "+6239109301",
    "photo" : "https://cloudinary.com",
    "idCardType" : "KTP",
    "idNumber" : "19901390193019",
    "updatedAt" : ISODate("2018-07-02T13:59:05.273Z"),
    "__v" : 0,
    "user_buddy" : [ 
        {
            "_id" : ObjectId("5b2dec013efecd0514a50561"),
            "createdAt" : ISODate("2018-06-23T06:43:11.092Z"),
            "username" : "lalaland",
            "email" : "lalaland@gmail.com",
            "fullname" : "Lala Princess",
            "nickname" : "lala",
            "password" : "$2a$08$LUs3fW/YPzkQeHvqH7QvTOr5H8RgqTGVvldFcUHFcfBGoRs.jn0hS",
            "updatedAt" : ISODate("2018-06-23T06:43:11.092Z"),
            "__v" : 0
        }, 
        {
            "_id" : ObjectId("5b2deca18966a405412d1266"),
            "createdAt" : ISODate("2018-06-23T06:45:48.578Z"),
            "username" : "yozawiratama",
            "email" : "yoza@yahoo.com",
            "fullname" : "Yoza Extra",
            "nickname" : "Yoza",
            "password" : "$2a$08$uZ/G61qtqdlSgSz.Qzt/i.ufiUBoPq7H8ViVwlJ1pA9SUZYUp34sO",
            "updatedAt" : ISODate("2018-06-23T06:45:48.578Z"),
            "__v" : 0
        }
    ]
} 

您可以看到伙伴的用户ID是 5b2deca18966a405412d1266 ,但是在user_buddy中返回两个文档,其中一个文档具有不同的_id

我希望它与buddies.userIdusers._id相匹配。

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

localFieldforeignField是字段名称。

应该是

db.getCollection('buddies').aggregate([
{
     $lookup:
       {
         from: "users",
         localField: "userId",
         foreignField: "_id",
         as: "user_buddy"
       }
  }
])

没有“ ObjectId”

ObjectId应该在文档本身中:

{
    "_id" : ObjectId("5b3a2fca0fe843093879b5bc"),
    "isVerified" : false,
    "isActivated" : false,
    "createdAt" : ISODate("2018-07-02T13:59:05.273Z"),
    "userId" : ObjectId("5b2deca18966a405412d1266")
    ....