如何在MongoDB中将子文档添加到子文档数组中

时间:2014-06-09 05:08:30

标签: mongodb mongodb-query

我有一个像mogodb这样的集合:

{
"_id" : ObjectId("5393006538efaae30ec2d458"),
"userName" : "shiva",
"userUnderApiKey" : 123456,
"groups" : [
    {
        "groupName" : "Default",
        "groupMembers" : [ ]
    }
]
}

我想在groups数组中添加一个新组作为子文档,如下所示

 {
"_id" : ObjectId("5393006538efaae30ec2d458"),
"userName" : "shiva",
"userUnderApiKey" : 123456,
"groups" : [
    {
        "groupName" : "Default",
        "groupMembers" : [ ]
    },

    {
        "groupName" : "Family",
        "groupMembers" : [ ]
    }
]
}

如何在子文档数组中插入新的子文档。任何帮助都是适当的

3 个答案:

答案 0 :(得分:3)

要向阵列添加新成员,您可以像往常一样使用$push

db.collection.update(
    { "_id": ObjectId("5393006538efaae30ec2d458") },
    { 
        "$push": {
            "groups": {
                "groupName" : "Family",
                "groupMembers" : [ ]
            }
        }
    }
)

如果您想要将成员添加到该成员包含的数组中,那么您需要匹配要添加的元素:

db.collection.update(
    { 
        "_id": ObjectId("5393006538efaae30ec2d458"),
        "groups.groupName" : "Family",
    },
    { 
        "$push": {
            "groups.$.groupMembers" : "bill"
        }
    }
)

答案 1 :(得分:2)

我想你会对$push

感兴趣
  

$ push运算符将指定值附加到数组。

$addToSet

  

$ addToSet运算符仅在数组中尚未包含值时才向数组添加值。如果值在数组中,$ addToSet不会修改数组。

您可以在上面的文档中找到示例。它会是这样的:

db.collection.update({
    _id: ObjectId("5393006538efaae30ec2d458")
}, {
    $push: {
        groups: {
            "groupName": "Family",
            "groupMembers": []
        }
    }
});

答案 2 :(得分:0)

SampleModel:
{
"Name":String,
"brandid": {
        type: Schema.ObjectId,
        ref: 'BrandList.BrandItems',
    }
}

BrandModel:
{
    "BrandName" : String,
    "BrandItems": [{
        "KG": Number,
        "_id" : {type: Schema.ObjectId}
    }]
}

如何将子文档数组对象id引用到另一个模型..以及如何使用populate这个“brandid”..

请给我解决这个问题的解决方案......

相关问题