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

f1n*_*1nn 20 insert exists updates mongodb node.js

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

{
    "instruments": ["A", "B", "C"],
    "_id": {
        "$oid": "508510cd6461cc5f61000001"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的收藏可能有这样的对象,但可能没有.我需要检查是否有关键的"乐器"对象存在(请notе,我不知道还有什么价值"仪器"就是在这个时候,它可能包含任何值或数组),如果存在-执行更新,否则 - 插入新值.我怎样才能做到这一点?

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

不起作用((

Gia*_* P. 23

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

collection.update(_query_, _update_, { upsert: true });
Run Code Online (Sandbox Code Playgroud)

请参阅有关upsert行为的文档.

$exists运营商的一个例子.

假设您的收藏中有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 }
Run Code Online (Sandbox Code Playgroud)

并且您想要查找具有特定字段的文档"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 ] }
Run Code Online (Sandbox Code Playgroud)

  • 你的_selector_是`{"instruments":{$ exists:true}}`而_document_是你想要更新它的东西,比如`$ set` something或`$ push`把一个元素附加到一个数组 (2认同)