NodeJS + Mongo:如果不存在则插入,否则 - 更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13010290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:30:38  来源:igfitidea点击:

NodeJS + Mongo: Insert if not exists, otherwise - update

node.jsmongodbinsertexistsupdates

提问by f1nn

I have an object in my mongodb collection. Its schema is:

我的 mongodb 集合中有一个对象。它的架构是:

{
    "instruments": ["A", "B", "C"],
    "_id": {
        "$oid": "508510cd6461cc5f61000001"
    }
}

My collection may have such object, but may not. I need to check if object with key "instruments" exists (please, notе, I don't know what value "instrument" is at this time, it may contain any value or an array), and if exists - perform update, otherwise – insert a new value. How can I do this?

我的收藏可能有这样的对象,但可能没有。我需要检查带有键“instruments”的对象是否存在(请注意,此时我不知道“instrument”是什么值,它可能包含任何值或数组),如果存在 - 执行更新,否则– 插入一个新值。我怎样才能做到这一点?

collection.find( {  "instruments" : { $exists : true } }, function(err, object){
    if (object) {
        //update
    } else {
        //insert
    }
});

doesn't work ((

不起作用((

回答by Gianfranco P.

If you want to insert one document if it is not found, you can use the upsertoption in the update()method:

如果想插入一个找不到的文档,可以使用方法中的upsert选项update()

collection.update(_query_, _update_, { upsert: true });

See docs for the upsertbehavior.

有关upsert行为,请参阅文档。

An example with the $existsoperator.

$exists运营商的例子。

Let's say you have 6 documents in your collection:

假设您的集合中有 6 个文档:

> db.test.find()
{ "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 }
{ "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] }
{ "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] }
{ "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] }
{ "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }
{ "_id": ObjectId("5495af60f83774152e9ea6b9"), "b": 2 }

and you want to find documents that have a certain field "a"), you can use find()method with the $existsoperator (node docs). Note: this will also return documents which field is an empty array.

并且您想查找具有特定字段的文档"a"),您可以使用find()带有$exists运算符的方法(节点文档)。注意:这也将返回字段为空数组的文档。

> db.test.find( { a: { $exists: true } } )
{ "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 }
{ "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] }
{ "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] }
{ "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] }
{ "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }