【问题标题】:Losing records when unwind results of lookup operation in MongoDB在 MongoDB 中展开查找操作的结果时丢失记录
【发布时间】:2017-09-10 07:40:14
【问题描述】:

我的“预订”表上有一个很长的查询,它工作得很好,除非我要求代理。

我们有一个“用户”表。此表包含用户、管理员、代理等。

“预订”总是有一个“用户”,所以 $lookup 总是很顺利。

“预订”有时有一个“代理”,但大多数时候该字段为空白“”。因此,当我执行 $lookup 时,它会破坏整个查询并且不返回任何内容。

我想进行 $lookup,但前提是“代理”字段不为空。 或者找到一种方法,如果 $lookup 失败,它不会破坏整个查询。

左侧是实际存在包含有效 users._id 的“代理”字段时 - 我们得到结果

右侧是“代理”字段缺失、包含空白值或包含无效值的情况。 - 在这里它破坏了整个查询。

这是一个带有数据的示例

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



booking Table
{
    "_id" : "AAAAA",
    "property" : "001",
    "user" : "U001",
    "agent" : "A001",
    "checkin" : 1493596800,
    "checkout" : 1494374400,
    "test" : "This one will always work"
}
{
    "_id" : "BBBBB",
    "property" : "001",
    "user" : "U001",
    "agent" : "",
    "checkin" : 1493596800,
    "checkout" : 1494374400,
    "test" : "This one has blank agent and does not work"
}
{
    "_id" : "CCCCC",
    "property" : "001",
    "user" : "U001",
    "checkin" : 1493596800,
    "checkout" : 1494374400,
    "test" : "This one has no agent and does not work"
}
{
    "_id" : "DDDDD",
    "property" : "001",
    "user" : "U001",
    "agent" : "XXXX",
    "checkin" : 1493596800,
    "checkout" : 1494374400,
    "test" : "This one has invalid agent and does not work"
}


users Table 
{
    "_id" : "U001",
    "name" : "I am USER"
}
{
    "_id" : "A001",
    "name" : "I am AGENT"
}

【问题讨论】:

  • 我试过这样的事情...... { $cond {if: {agent $ne ""}, then: {$lookup code.....} - 但无法让它工作。
  • [docs.mongodb.com/manual/reference/operator/aggregation/cond/](阅读此文档将帮助您完成)
  • @ShumiGupta 已经这样做了 - 页面很糟糕,例子很糟糕。 { $cond: [ , , ] } 我试过了,它不起作用 - 它不会让我将 $lookup 放入 true-case。
  • 您可以尝试在聚合数组的开头包含{ $match : { agent: { $exists : true, $ne : "" } } } 吗? Like -> [ { $match: ... }, { $lookup: ... }, { $unwind: ... } ] 如果agent 字段存在且不等于"",则应用聚合的其余部分
  • @bureaquete 是的,请这样做,我可以结束这个问题

标签: mongodb mongodb-query


【解决方案1】:

当您将$lookup 的结果传送到$unwind 时,会出现问题,该结果以查找结果数组所在的结果字段为目标,查找操作的空结果将被展开删除,您的数据丢失发生在该位置。回溯您的聚合逻辑并将preserveNullAndEmptyArrays 选项添加到有罪的$unwind 步骤。这将阻止该步骤中的记录丢失,从而解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2020-02-06
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    相关资源
    最近更新 更多