mongo 可以插入数组数据吗? [英] Can mongo upsert array data?

查看:28
本文介绍了mongo 可以插入数组数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 mongo 文档.

I have a mongo document like this.

{
    "_id" : ObjectId("50b429ba0e27b508d854483e"),
    "array" : [
        {
            "id" : "1",
            "letter" : "a"
        },
        {
            "id" : "2",
            "letter" : "b"
        }
    ],
    "tester" : "tom"
}

我希望能够使用单个 mongo 命令插入和更新 array,而不是在 find() 中使用条件,然后运行 ​​insert()update() 取决于对象的存在.

I want to be able to insert and update the array with a single mongo command and not use a conditional within a find() then run insert() and update() depending on the presence of the object.

id 是我想成为选择器的项目.所以如果我用这个更新数组:

The id is the item I want to be the selector. So if I update the array with this:

{
    "id" : "2",
    "letter" : "c"
}

我必须使用 $set 语句

db.soup.update({
    "tester":"tom",
    'array.id': '2'
}, {
    $set: {
        'array.$.letter': 'c'
    }
})

如果我想在数组中插入一个新对象

And if I want to insert a new object into the array

{
    "id" : "3",
    "letter" : "d"
}

我必须使用 $push 语句

db.soup.update({
    "tester":"tom"
}, {
    $push: {
        'array': {
            "id": "3",
            "letter": "d"
        }
    }
})

我需要一种数组项的 upsert.

I need a sort of upsert for an array item.

我必须以编程方式执行此操作还是可以通过单个 mongo 调用执行此操作?

Do I have to do this programmatically or can I do this with a single mongo call?

推荐答案

我不知道有什么选项可以像 MongoDB 2.2 那样向上插入到嵌入式数组中,因此您可能必须在应用程序代码中处理这个问题.

I'm not aware of an option that would upsert into an embedded array as at MongoDB 2.2, so you will likely have to handle this in your application code.

鉴于您想将嵌入的数组视为某种虚拟集合,您可能需要考虑将数组建模为一个单独的集合.

Given that you want to treat the embedded array as sort of a virtual collection, you may want to consider modelling the array as a separate collection instead.

您不能基于嵌入数组中的字段值执行 upsert,但您可以使用 $addToSet 插入一个不存在的嵌入文档:

You can't do an upsert based on a field value within an embedded array, but you could use $addToSet to insert an embedded document if it doesn't exist already:

db.soup.update({
    "tester":"tom"
}, {
    $addToSet: {
        'array': {
            "id": "3",
            "letter": "d"
        }
    }
})

这不适合您通过数组元素的 id 进行匹配的确切用例,但如果您知道预期的当前值,可能会很有用.

That doesn't fit your exact use case of matching by id of the array element, but may be useful if you know the expected current value.

这篇关于mongo 可以插入数组数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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