如何在MongoDB内部列表中插入元素? [英] How to insert an element to MongoDB internal list?

查看:412
本文介绍了如何在MongoDB内部列表中插入元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中存储了以下文档:

I have the following doc stored in MongoDB:

{
    name: 'myDoc',
    list: [
        {
            id:1
            items:[
                {id:1, name:'item1'},
                {id:2, name:'item2'}
            ]
        },
        {
            id:2
            items:[
                {id:1, name:'item1'},
                {id:3, name:'item3'}
            ]
        }
    ]
}

我找到了一种使用$addToSet将元素添加到列表"中的方法,但是我找不到一种将项添加到列表"的特定列表中的方法.

I found a way to add an element to 'list' using $addToSet but I couldn't find a way to add to a specific list of 'items' an item.

例如 我得到以下信息:

e.g. I get the following:

{id:5, name:'item5'} 

,我想将其添加到ID为2的列表中的元素项中.

and I want to add it to the element's item in the list with id:2.

推荐答案

一种方法是使用$push:

db.col.update(
    { name: 'doc', 'list.id': 2 }, 
    {$push: {'list.$.items': {id: 5, name: 'item5'}}}
)

http://docs.mongodb.org/manual/reference/operator/push/

您也可以将$push替换为(可能)$addToSet之类的其他运算符,以获取所需的确切结果.

You can also replace $push with other operators like (possibly) $addToSet to get the exact results you are looking for.

这篇关于如何在MongoDB内部列表中插入元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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