【问题标题】:MongoDB getting $lookup to return only one recordMongoDB 获得 $lookup 以仅返回一条记录
【发布时间】:2017-08-30 00:36:20
【问题描述】:

这是预订表

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"
    }
]

这是我的查询,效果很好,除了每条预订记录都会附加所有用户,而不仅仅是 users._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

【问题讨论】:

  • 实际上使用 $unwind 它会为每个用户创建一个预订记录 = 2 个预订 x 5 个用户 = 结果中的 10 个记录 - 如果没有 $unwind 它会在每个预订记录中创建所有用户。
  • 你把localFieldforeignField 搞混了。试试localField: "user", foreignField: "_id",
  • @Veeram 我都试过了,但得到了完全相同的结果。 10 条记录(2 个预订 x 5 个用户)。这真的很奇怪。
  • 这几乎就像我写错了字段名称,或者错误的大小写或其他东西,但我看不出有什么问题。
  • 这很奇怪。我在 3.2.6 上使用我建议的编辑运行了您的代码,它为每个预订文档返回了一个匹配的用户。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您混淆了localFieldforeignField

尝试localField: "user", foreignField: "_id" 不带别名/集合名称。

来自文档

localField:来自输入文档的字段,
foreignField:来自“from”集合的文档的字段,

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

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

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

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 2017-12-23
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    相关资源
    最近更新 更多