让我们假设我有一个像这样的MongoDB集合:
[
{someId: 1, someProp: prop1, isOpen: true},
{someId: 2, someProp: prop1, isOpen: true},
{someId: 3, someProp: prop1, isOpen: true},
{someId: 4, someProp: prop1, isOpen: true},
]
我想用一组对象来调用它,但是其中一些对象是新的,有些需要覆盖现有的文档.
所以让我们说我的数组看起来像这样:
[
{someId: 1, someProp: prop1, isOpen: true},
{someId: 2, someProp: prop1, isOpen: true},
{someId: 5, someProp: prop1, isOpen: true},
{someId: 6, someProp: prop1, isOpen: true},
]
如何编写执行以下操作的MongoDB查询.
如果someId匹配我的第二个数组中的对象,只需将isOpen更改为false.
如果someId与任何对象都不匹配,则将它们插入到集合中.
所以在我运行我的查询后,我最终得到:
[
{someId: 1, someProp: prop1, isOpen: false},
{someId: 2, someProp: prop1, isOpen: false},
{someId: 3, someProp: prop1, isOpen: true},
{someId: 4, someProp: prop1, isOpen: true},
{someId: 5, someProp: prop1, isOpen: true},
{someId: 6, someProp: prop1, isOpen: true},
]
调用forEach()并使用以下是一个好主意:
db.books.update(
{ item: "ZZZ135" },
{
item: "ZZZ135",
stock: 5,
tags: [ "database" ]
},
{ upsert: true }
)
…在循环?可能不是.这意味着多次调用db.有没有更有效的方法呢?
解决方法:
基本上你需要bulkWrite
操作与upsert
const array = [
{ someId: 1, someProp: prop1, isOpen: true },
{ someId: 2, someProp: prop1, isOpen: true },
{ someId: 5, someProp: prop1, isOpen: true },
{ someId: 6, someProp: prop1, isOpen: true }
]
Model.bulkWrite(
array.map((data) =>
({
updateOne: {
filter: { someId: data.someId },
update: { $set: { isOpen: false, someProp: data.someProp } },
upsert: true
}
})
)
})
会给你输出
[
{ someId: 1, someProp: prop1, isOpen: false },
{ someId: 2, someProp: prop1, isOpen: false },
{ someId: 3, someProp: prop1, isOpen: true },
{ someId: 4, someProp: prop1, isOpen: true },
{ someId: 5, someProp: prop1, isOpen: true },
{ someId: 6, someProp: prop1, isOpen: true }
]