NodeJS + Mongo:如果不存在则插入,否则-更新 [英] NodeJS + Mongo: Insert if not exists, otherwise - update

查看:222
本文介绍了NodeJS + Mongo:如果不存在则插入,否则-更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mongodb集合中有一个对象.其架构为:

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

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

我的收藏夹可能有这样的对象,但可能没有.我需要检查具有键"instruments"的对象是否存在(请注意,我目前不知道"instrument"的值是什么,它可能包含任何值或数组),并且如果存在-执行更新,否则-插入新值.我该怎么办?

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?

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

不起作用((

推荐答案

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

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

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

有关 upsert 行为.

使用$exists运算符的示例.

假设您的收藏夹中有6个文档:

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

> 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()方法与节点文档).注意:这还将返回文档,该字段为空数组.

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

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

这篇关于NodeJS + Mongo:如果不存在则插入,否则-更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆