gpt4 book ai didi

mongodb - 如何从文档中的列表中查询,其中 2 个条件必须同时为真

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

我有以下 3 个虚拟文件。我希望找到 end_terminal 为“LGA”的所有文档 AND 值等于或大于 0.50 对于同一个 end_terminal。
为此,我这样做:

db.getCollection('test_coll').aggregate(
[
{'$match': {'$and':
[
{'return_options.end_terminal':'LGA'},
{'return_options.value':{'$gte':0.5}}
]

}
}
]

)
但结果是前 2 个文档(我认为查询会查看任何文档 >= 0.5)
/* 1 */
{
"_id" : ObjectId("60a2c0621e5f043b735e36ef"),
"car_id" : 1900641778,
"terminal" : "JFK",
"return_options" : [
{
"end_terminal" : "LGA",
"value" : 0.81
},
{
"end_terminal" : "YYZ",
"value" : 0.15
},
{
"end_terminal" : "MIA",
"value" : 0.04
}
]
}

/* 2 */
{
"_id" : ObjectId("60a7ce2c3df71a85997cc248"),
"car_id" : 1900641779,
"terminal" : "YYZ",
"return_options" : [
{
"end_terminal" : "JFK",
"value" : 0.5
},
{
"end_terminal" : "ORD",
"value" : 0.1
},
{
"end_terminal" : "LGA",
"value" : 0.4
}
]
}

/* 3 */
{
"_id" : ObjectId("60a7cf1b3df71a85997cc3f8"),
"car_id" : 1900641778,
"terminal" : "ORD",
"return_options" : [
{
"end_terminal" : "EWR",
"value" : 0.71
},
{
"end_terminal" : "YYZ",
"value" : 0.25
},
{
"end_terminal" : "LAS",
"value" : 0.04
}
]
}
enter image description here
另外 - 如何仅投影来自 return_options 的项目的结果。换句话说,不要投影列表中的任何项目 return_options如果不符合查询条件(不关心YYZ,MIA)只有LGA。

最佳答案

您可以使用 $filter

  • 如果需要排除不满足任何条件的文件,可以使用$match .否则你只能使用 $project

  • 这是代码
    db.collection.aggregate([
    {
    "$match": {
    "return_options.end_terminal": "LGA",
    "return_options.value": { $gte: 0.5 }
    }
    },
    {
    $project: {
    return_options: {
    "$filter": {
    "input": "$return_options",
    "cond": {
    "$and": [
    { $eq: [ "$$this.end_terminal", "LGA" ] },
    { "$gte": [ "$$this.value", 0.5 ] }
    ]
    }
    }
    }
    }
    },
    {
    "$match": {
    $expr: { $ne: [ "$return_options", [] ] }
    }
    }
    ])
    工作Mongo playground

    关于mongodb - 如何从文档中的列表中查询,其中 2 个条件必须同时为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67639947/

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