gpt4 book ai didi

arrays - 仅在数组的第一个元素具有特定字段值的情况下进行 Mongo 匹配

转载 作者:行者123 更新时间:2023-12-04 17:49:10 24 4
gpt4 key购买 nike

我在下面有一个查询,它从一个大型嵌套文档中提取几个值。它告诉我每个订单的用户 ID 和第一个项目名称。

这工作正常,但我希望它只返回第一项名称不为空且不为空的记录。我不知道如何向下面的 $match 运算符添加第二个查询来实现此目的

db.getCollection('Orders').aggregate
([
{ $match : { "Items.1" : { $exists : true }}, ???},
{ $project: {
_id:0,
'UserId': '$User.EntityId',
'ItemName': {$arrayElemAt: ['$Items.Details.ItemName', 0]}
}
}
]);

编辑以显示示例文档

{
"_id" : "order-666156",
"State" : "ValidationFailed",
"LastUpdated" : {
"DateTime" : ISODate("2017-09-26T08:54:16.241Z"),
"Ticks" : NumberLong(636420128562417375)
},
"SourceOrderId" : "666156",
"User" : {
"EntityId" : NumberLong(34450),
"Name" : "Bill Baker",
"Country" : "United States",
"Region" : "North America",
"CountryISOCode" : "US",
},
"Region" : null,
"Currency" : null,
"Items" : [
{
"ClientOrderId" : "18740113",
"OrigClientOrderId" : "18740113",
"Quantity" : NumberDecimal("7487.0"),
"TransactDateTime" : {
"DateTime" : Date(-62135596800000),
"Ticks" : NumberLong(0)
},
"Text" : null,
"LocateRequired" : false,
"Details" : {
"ItemName" : "Test Item 1",
"ItemCost" : 1495.20
}
},
{
"ClientOrderId" : "18740116",
"OrigClientOrderId" : "18740116",
"Quantity" : NumberDecimal("241.0"),
"TransactDateTime" : {
"DateTime" : Date(-62135596800000),
"Ticks" : NumberLong(0)
},
"Text" : null,
"LocateRequired" : false,
"Details" : {
"ItemName" : "Test Item 2",
"ItemCost" : 2152.64
}
}
]

}

最佳答案

您需要将这两个条件添加到现有的 $match(不为空且不为空)以将项目检查为:

 $match : { "Items.1" : { $exists : true, "$ne": null,"$ne":""}

如果你想检查元素 Items[0].Details.ItemName 你可以使用运算符 $and

{ $match : { 
$and: [
{"Items.1" : { $exists : true }},
{"Items.Details.ItemName" : { $ne : null}},
{"Items.Details.ItemName" : { $ne : ""}},
]
}},

关于arrays - 仅在数组的第一个元素具有特定字段值的情况下进行 Mongo 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484782/

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