gpt4 book ai didi

mongodb - 如果在数组中找不到匹配项,则返回第一个元素

转载 作者:可可西里 更新时间:2023-11-01 09:33:11 26 4
gpt4 key购买 nike

我有以下文件:

{
_id: 123,
state: "AZ",
products: [
{
product_id: 1,
desc: "P1"
},
{
product_id: 2,
desc: "P2"
}
]
}

我需要编写一个查询来返回产品数组中的单个元素,其中 state 为“AZ”且 product_id 为 2。如果未找到匹配的 product_id,则返回产品数组中的第一个(或任何)元素.

例如:如果 product_id 为 2(找到匹配项),则结果应为:

products: [
{
product_id: 2,
desc: "P2"
}
]

如果 product_id 为 3(未找到),则结果应为:

products: [
{
product_id: 1,
desc: "P1"
}
]

找到匹配时我能够满足一个条件,但不确定如何在同一查询中满足第二个条件:

db.getCollection('test').find({"state": "AZ"}, {_id: 0, state: 0, products: { "$elemMatch": {"product_id": "2"}}})

我也尝试过使用聚合管道,但找不到可行的解决方案。

注意:这与以下问题不同,因为如果未找到匹配项,我需要返回一个默认元素: Retrieve only the queried element in an object array in MongoDB collection

最佳答案

你可以试试下面的聚合

基本上你需要$filter products 数组并检查 $cond如果它不包含任何元素或不等于 [] 那么你必须$sliceproducts 数组的第一个元素。

db.collection.aggregate([
{ "$addFields": {
"products": {
"$cond": [
{
"$eq": [
{ "$filter": {
"input": "$products",
"cond": { "$eq": ["$$this.product_id", 2] }
}},
[]
]
},
{ "$slice": ["$products", 1] },
{ "$filter": {
"input": "$products",
"cond": { "$eq": ["$$this.product_id", 2] }
}}
]
}
}}
])

甚至使用 $let聚合

db.collection.aggregate([
{ "$addFields": {
"products": {
"$let": {
"vars": {
"filt": {
"$filter": {
"input": "$products",
"cond": { "$eq": ["$$this.product_id", 2] }
}
}
},
"in": {
"$cond": [
{ "$eq": ["$$filt", []] },
{ "$slice": ["$products", 1] },
"$$filt"
]
}
}
}
}}
])

关于mongodb - 如果在数组中找不到匹配项,则返回第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613870/

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