我的mongodb集合中有一个对象。它的架构是:
{
"instruments": ["A", "B", "C"],
"_id": {
"$oid": "508510cd6461cc5f61000001"
}
}
我的收藏可能有这样的对象,但可能没有。我需要检查是否存在具有关键“乐器”的对象(请,不知道,此时我不知道“乐器”的值是什么,它可能包含任何值或数组),以及if exists - 执行更新,否则 - 插入新值。我怎么能这样做?
collection.find( { "instruments" : { $exists : true } }, function(err, object){
if (object) {
//update
} else {
//insert
}
});
不起作用((
答案 0 :(得分:21)
如果要插入一个文档(如果找不到),可以使用upsert
方法中的update()
选项:
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 docs)。注意:这也将返回哪个字段为空数组的文档。
> 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 ] }