MongoDB获取$ lookup只返回一条记录

时间:2017-04-04 17:08:12

标签: mongodb mongodb-query aggregation-framework

这是预订表

booking [
    {
        "_id" : "0J0DR",
        "user" : "MN90L",
        "property" : "58669471869659d70b424ea7",
        "checkin" : 1488758400,
        "checkout" : 1489363200
    },
    {
        "_id" : "0PDLR",
        "user" : "7CSEF",
        "property" : "586694ea869659d70b424eb3",
        "checkin" : 1488326400,
        "checkout" : 1498780800
    }
]

这是用户表

users [
    {
        "_id" : "4M4KE",
        "email" : "test@vest.com",
        "name" : "Torben"
    },
    {
        "_id" : "MN90L",
        "email" : "mr@booker.com",
        "name" : "Mr. Booker"
    },
    {
        "_id" : "GF37A",
        "email" : "test@test.com",
        "name" : "Whatever"
    },
    {
        "_id" : "7CSEF",
        "email" : "miss@booker.com",
        "name" : "Miss. Booker"
    },
    {
        "_id" : "W0LG9",
        "email" : "xxx@yyy.com",
        "name" : "Whatever"
    }
]

这是我的查询效果很好,除了每个预订记录都让所有用户都连接而不仅仅是用户._id = booking.user

db.getCollection('booking').aggregate([{
    $match: {
        checkin : {$lte: (1512145439)},
        checkout: {$gte: (1483203600)},
    }
}, {
    $lookup: {
        from: "users",
        localField: "users._id",
        foreignField: "booking.user",
        as: "users"
    }   
}, {
    $unwind: "$users"
}])

我做错了什么?

我尝试使用和不使用$ unwind。

我需要做一些$ match还是localField foreignField?

我的db.version()= 3.2.12

1 个答案:

答案 0 :(得分:1)

您已localFieldforeignField混淆了。

尝试不使用别名/集合名称的localField: "user", foreignField: "_id"

来自docs

  

localField:来自输入文档的字段,
  foreignField:" from"的文档中的字段收集,

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

使用点符号时,MongoDB认为您正在尝试访问嵌入文档中的字段。

https://docs.mongodb.com/manual/core/document/#document-dot-notation