MongoDB批量运算符,如果不存在则插入 [英] MongoDB bulk operator, insert if not exists
问题描述
我正在使用MongoDB批量操作来插入文档.
I'm using the MongoDB bulk operation to insert documents.
我想做的就是插入,仅在找不到文档的情况下-如果找到文档(即upsert),我不想更新.
What I'd like to do is insert, only if no document is found - I don't want to update if it is found (i.e., upsert).
任何想法如何做到这一点?
Any ideas how to do this?
但是,即使在这种情况下:
However, even in this case:
var obj = {
item: 'test'
}
bulk.find({ item: {$ne : obj.item}}).upsert().updateOne(obj);
bulk.execute();
这似乎并没有实际插入任何东西(如果找不到的话).
This doesn't seem to actually insert anything if not found.
我想对此进行更新以澄清更多信息.
I wanted to update this to clarify a bit more.
我正在尝试使用批量api执行两项操作,一项是更新,一项是插入.
There are two operations I'm trying to perform, using bulk api, one is to update and one is to insert.
文档如下:
{
item: 'test',
categories: [{
name: 'one',
attr: 'two'
}]
}
我想做的是,如果找不到项目值,则插入obj.但是,如果找到它,则如果没有找到categories.name
,则将$push
类别对象作为categories
数组.如果找到该文档且该类别存在,则什么也不做.
What I'd like to do is if the item value is not found, then insert the obj. However, if it is found, then if categories.name
is not found, $push
the category object to the categories
array. If the document is found and the category exists, do nothing.
推荐答案
您想要保持相同的更新操作,但要更改查询.从文档:>
What you'd want is to maintain the same update operation but change the query. From the documentation:
Bulk.find(<query>).upsert().update(<update>);
Bulk.find(<query>).upsert().updateOne(<update>);
Bulk.find(<query>).upsert().replaceOne(<replacement>);
With the upsert option set to true, if no matching documents exist for the Bulk.find()
condition, then the update or the replacement operation performs an insert. If a matching document does exist, then the update or replacement operation performs the specified update or replacement.
更改查询以查找满足以下条件的文档:
Change the query to look for documents that satisfy the condition:
var obj = { item: 'test' };
bulk.find(obj).upsert().updateOne({ $setOnInsert: obj });
bulk.execute();
In the above, if the a matching document does exist, then the update with $setOnInsert
does nothing as the update operation does not result in an insert, having found a document that matches the query.
这篇关于MongoDB批量运算符,如果不存在则插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!