【问题标题】:NodeJS + Mongo: Insert if not exists, otherwise - updateNodeJS + Mongo:如果不存在则插入,否则 - 更新
【发布时间】:2012-10-12 04:41:27
【问题描述】:

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

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

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

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

不起作用((

【问题讨论】:

    标签: node.js mongodb insert exists updates


    【解决方案1】:

    如果你想插入一个找不到的文档,可以使用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 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 ] }
    

    【讨论】:

    • 这很好,谢谢,但我实际上不知道该放置什么作为“选择器”。最好的方法是像“instrument:[...]”这样的东西,但我不知道“instrument”的当前值是多少。
    • 你的 selector{ "instruments" : { $exists : true } }document 是你想要更新的内容,例如 $set something 或 $push将元素附加到数组
    • 我只想使用我在表上定义的唯一键来确定更新与否。插入。我不想在选择器参数中再次指定它。有没有办法做到这一点?
    • 如果 upsert 为真并且有符合查询条件的文档,update() 执行更新。查看行为docs.mongodb.org/manual/reference/method/db.collection.update/… - 我相信这比在您的应用程序中手动编码要好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 2014-10-23
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多