gpt4 book ai didi

MongoDB 让 $lookup 只返回一条记录

转载 作者:行者123 更新时间:2023-12-04 03:13:17 25 4
gpt4 key购买 nike

这是预订表

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

最佳答案

您混淆了 localFieldforeignField

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

来自文档

localField: field from the input documents,
foreignField: field from the documents of the "from" collection,

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

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

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

关于MongoDB 让 $lookup 只返回一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com