Arrays MongoDB-增量嵌套文档数组,其中不为Null
我有以下示例文档结构:Arrays MongoDB-增量嵌套文档数组,其中不为Null,arrays,mongodb,increment,embedded-database,documents,Arrays,Mongodb,Increment,Embedded Database,Documents,我有以下示例文档结构: { "_id" : 1, "distributor" : "Jackson", "systems" : [ { "name" : "XBOX", "quantity" : null, }, { "name" : "PlayStation", "quantity" : 10, },
{
"_id" : 1,
"distributor" : "Jackson",
"systems" : [
{
"name" : "XBOX",
"quantity" : null,
},
{
"name" : "PlayStation",
"quantity" : 10,
},
{
"name" : "Nintendo",
"quantity" : 20,
},
{
"name" : "Atari",
"quantity" : null,
},
],
"games" : [
{
"name" : "Call of Duty",
"quantity" : 5
},
{
"name" : "Super Mario Bros",
"quantity" : null,
},
{
"name" : "Madden",
"quantity" : 4,
],
"comments" : null,
"contact" : "Bill"
}
我想将每个notnull
嵌入文档的数量增加1
。到目前为止,我能够让它更新第一个find not null条目(在本例中为Playstation),但没有其他内容
我期望的结果如下所示:
{
"_id" : 1,
"distributor" : "Jackson",
"systems" : [
{
"name" : "XBOX",
"quantity" : null,
},
{
"name" : "{PlayStation}",
"quantity" : 11,
},
{
"name" : "Nintendo",
"quantity" : 21,
},
{
"name" : "Atari",
"quantity" : null,
},
],
"games" : [
{
"name" : "Call of Duty",
"quantity" : 6
},
{
"name" : "Super Mario Bros",
"quantity" : null,
},
{
"name" : "Madden",
"quantity" : 5,
],
"comments" : null,
"contact" : "Bill"
}
谢谢你的指导 如果您使用的是MongoDB 3.6或更高版本,则可以使用
数组筛选器只是将您的条件应用于数组的每个元素,并在该元素匹配时执行更新。听起来您需要聚合。到目前为止,您尝试了哪些命令?你也应该把这些贴上去。
db.col.update(
{_id: 1},
{ $inc: { "systems.$[elem].quantity": 1, "games.$[elem].quantity": 1 } },
{ arrayFilters: [ { "elem.quantity": { $ne: null } } ] });