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

26

我在我的 mongodb 集合中有一个对象。它的模式为:

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

我的集合可能有这样的对象,也可能没有。我需要检查是否存在具有键“instruments”的对象(请注意,此时我不知道“instrument”值是什么,它可能包含任何值或数组),如果存在-执行更新,否则-插入新值。我该怎么做?

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

无法工作 ((

1个回答

24

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

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

查看关于 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 }

如果您想查找具有特定字段"a"的文档,您可以使用find()方法与$exists运算符(node文档)。注意:这也会返回字段为空数组的文档。

> 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 ] }

很好,谢谢,但我实际上不知道该放什么作为“选择器”。最好的方法将是类似于“instrument:[...]”,但我不知道“instrument”的当前值是什么。 - f1nn
2
你的_selector_是{ "instruments" : { $exists : true } },而_document_是你想要更新的内容,例如使用$set来设置某个值或者使用$push来向数组中追加元素。 - Gianfranco P.
1
我只想使用我在表格上定义的唯一键来确定更新还是插入。我不想在选择器参数中再次指定它。有没有办法这样做? - sming
如果upsert为true并且有符合查询条件的文档,则update()执行更新。请参见行为http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option - 我认为这比在应用程序中手动编写代码更好。 - Gianfranco P.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接