有没有一种方法可以匹配mongodb中子文档数组中的2个特定字段值



我有以下格式的数据:

{ 
"_id" : ObjectId("5f281caf3494701c38711e96"), 
"WidgetId" : "0233261", 
"Specs" : [
{
"WidgetType" : "A",
"AmountLow" : NumberLong(0), 
"AmountHigh" : NumberLong(0), 
}, 
{
"WidgetType: "A",
"AmountLow" : NumberLong(0), 
"AmountHigh" : NumberLong(500), 
}, 
{
"WidgetType" : "A"
"AmountLow" : NumberLong(1), 
"AmountHigh" : NumberLong(1000), 
}
]
}

然而,数据是错误的,因为我不能有"Specs.AmountLow" = 0"Specs.AmountHigh" > 0的值,它们应该是0/0或>0/>0.

我找不到具有"Specs.AmountLow" = 0"Specs.AmountHigh" > 0特定组合的文档。以下是我尝试过但没有成功的两个查询:

尝试1:

db.widgets.find(
{ 
"Specs.AmountLow" : NumberLong(0), 
"Specs.AmountHigh" : { 
"$gt" : NumberLong(0)
}
}, 
{ 
"WidgetId" : 1.0, 
"Specs.AmountLow" : 1.0, 
"Specs.AmountHigh" : 1.0
}
)

只要AmountLow为0或AmountHigh大于0,上述查询就会发回所有结果,因此在示例数据中,即使没有0/>0值

我下一次尝试了这个:

db.widgets.find(
{ 
"$and" : [
{ 
"Specs.$.AmountLow" : NumberLong(0)
}, 
{ 
"Specs.$.AmountHigh" : { 
"$gt" : NumberLong(0)
}
}
]
}, 
{ 
"WidgetId" : 1.0, 
"Specs.AmountLow" : 1.0,
"Specs.AmountHigh" : 1.0
}
);

然而,这一次没有返回任何结果,即使我用0/>0值

如何编写查询来查找AmountLow = 0AmountHigh > 0的特定子文档组合,以及作为推论,如何仅更新这些记录以具有AmountLow = 1

预期结果:

{ 
"_id" : ObjectId("5f281caf3494701c38711e96"), 
"WidgetId" : "0233261", 
"Specs" : [
{
"WidgetType: "A",
"AmountLow" : NumberLong(0), 
"AmountHigh" : NumberLong(500), 
}
]
}

你可以试试,

当您使用$-position时,这将只返回数组和数组中的一个匹配文档

  • 使用$elemMatch进行数组元素匹配
  • 在投影中使用CCD_ 11位置在阵列字段名称之后
db.widgets.find({
Specs: {
$elemMatch: {
AmountLow: 0,
AmountHigh: {
$gt: 0
}
}
}
},
{
_id: 1,
WidgetId: 1,
"Specs.$": 1
})

游乐场


与上面的示例不同,您可以使用aggregate((,这个示例将返回数组中的所有匹配文档,

  • $filter根据条件从数组中获取筛选后的文档
db.widgets.aggregate([
{
$addFields: {
Specs: {
$filter: {
input: "$Specs",
cond: {
$and: [
{ $eq: ["$$this.AmountLow", 0] },
{ $gt: ["$$this.AmountHigh", 0] }
]
}
}
}
}
}
])

游乐场

最新更新