用计数器更新
Upsert with counter
我有一个 fruit
集合,其中包含以下文档:
{
tag: "Apple",
count: 3
},
{
tag: "Banana",
count: 2
}
我得到了带有标签和值的新文档。值 1 表示增加计数器,值 -1 表示减少计数器
{
tag: "Coconut",
value: 1
},
{
tag: "Banana",
count: -1
}
upsert 的结果应该是:
{
tag: "Apple",
count: 3
},
{
tag: "Banana",
count: 1 // previously 2, decrease counter by 1
},
{
tag: "Coconut",
count: 1 // Did not exist, so add and set counter to 1
}
此外,如果 count
减少到 0(或更少),则从集合中删除文档。
所以如果我接下来得到这个:
{
tag: "Apple",
count: 1
},
{
tag: "Banana",
count: -1
}
下一个 upsert 的结果应该是
{
tag: "Apple", // previously 3, increase by 1
count: 4
},
// {
// tag: "Banana",
// count: 0 // Remove from collection
// },
{
tag: "Coconut",
count: 1
}
如何在 mongodb 中以简洁的方式实现此目的?
您可以使用bulkWrite
db.myCollection.bulkWrite([
{
updateOne: {
filter: { tag: "Banana" } ,
update: { $inc: { "count": -1 } },
upsert : true
}
},
{
updateOne: {
filter: { tag: "Coconut" } ,
update: { $inc: { "count": 1 } },
upsert: true
}
},
{
deleteMany : { // delete records records if count is 0 or less
filter : { count: { $lte: 0 } }
}
}
])
我有一个 fruit
集合,其中包含以下文档:
{
tag: "Apple",
count: 3
},
{
tag: "Banana",
count: 2
}
我得到了带有标签和值的新文档。值 1 表示增加计数器,值 -1 表示减少计数器
{
tag: "Coconut",
value: 1
},
{
tag: "Banana",
count: -1
}
upsert 的结果应该是:
{
tag: "Apple",
count: 3
},
{
tag: "Banana",
count: 1 // previously 2, decrease counter by 1
},
{
tag: "Coconut",
count: 1 // Did not exist, so add and set counter to 1
}
此外,如果 count
减少到 0(或更少),则从集合中删除文档。
所以如果我接下来得到这个:
{
tag: "Apple",
count: 1
},
{
tag: "Banana",
count: -1
}
下一个 upsert 的结果应该是
{
tag: "Apple", // previously 3, increase by 1
count: 4
},
// {
// tag: "Banana",
// count: 0 // Remove from collection
// },
{
tag: "Coconut",
count: 1
}
如何在 mongodb 中以简洁的方式实现此目的?
您可以使用bulkWrite
db.myCollection.bulkWrite([
{
updateOne: {
filter: { tag: "Banana" } ,
update: { $inc: { "count": -1 } },
upsert : true
}
},
{
updateOne: {
filter: { tag: "Coconut" } ,
update: { $inc: { "count": 1 } },
upsert: true
}
},
{
deleteMany : { // delete records records if count is 0 or less
filter : { count: { $lte: 0 } }
}
}
])