首页 文章

将新项值添加到mongoDB中的嵌入文档中

提问于
浏览
1

我有一份文件:

{
        "_id" : ObjectId("550c00f81bcc15211016699b"),
        "name" : "book3",
        "author" : "mno",
        "publisher" : "pub",
        "testa" : [
                {
                        "item1" : "item1",
                        "item2" : "item2"
                }
        ]
}

我想做的就是在testa中添加另一个项目,如:

{
        "_id" : ObjectId("550c00f81bcc15211016699b"),
        "name" : "book3",
        "author" : "mno",
        "publisher" : "pub",
        "testa" : [
                {
                        "item1" : "item1",
                        "item2" : "item2",
                        "item3  : "item3"
                }
        ]
}

我试过用

db.books.update(
   { "author":"mno" },
   { $addToSet: { testa : {"item3":"item3"} } }
)

这给了

{
        "_id" : ObjectId("550c05261bcc15211016699c"),
        "name" : "book3",
        "author" : "mno",
        "publisher" : "pub",
        "testa" : [
                {
                        "item1" : "item1",
                        "item2" : "item2"
                },
                {
                        "item3" : "item3"
                }
        ]
}

我试过

db.books.update(
   { "author":"mno" , "testa.item1" : "item1"},
   { $set : {"testa.0" : {"item3":"item3"}}},
   {upsert : true / false}
   )

这给了

{
        "_id" : ObjectId("550c05fa1bcc15211016699d"),
        "name" : "book3",
        "author" : "mno",
        "publisher" : "pub",
        "testa" : [
                {
                        "item3" : "item3"
                }
        ]
}

我做错了什么,我到处检查Insert an embedded document to a new field in mongodb documentUpdate or replace an embedded document in MongoDB collection

我尝试过很奇怪的东西......但是......请帮我查询一下

我也尝试使用C#驱动程序

WriteConcernResult res = booksColl.Update(query, Update.Set("testa.$.item1", "itemedited"),UpdateFlags.Upsert);

2 回答

  • 0

    以下陈述应该有效

    db.books.update(
       { "author":"mno" },
       { $set: { "testa.0.item3" : "item3"} } 
    )
    

    您可以使用点表示法来指定数组中的项目,然后您可以将新的 item3 字段设置为您希望的值 . 你在上面的例子中几乎没有 - 你只需要指定 "testa.0.item3" 而不是 "testa.0"

    我同意上面的@chridam的评论,并且更改架构会使文档更容易使用 . 它现在可能是一些额外的工作,但从长远来看它会拯救你 .

  • 1

    实际上你没有一个项目集合,你有一个文件集合,其中有项目作为键:值,如果这是目标,更新可能是:

    > db.books.update({ "author":"mno" },{$set: {"testa.0.item3":"item3"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.books.find().pretty()
    {
            "_id" : ObjectId("550c00f81bcc15211016699b"),
            "name" : "book3",
            "author" : "mno",
            "publisher" : "pub",
            "testa" : [
                    {
                            "item1" : "item1",
                            "item2" : "item2",
                            "item3" : "item3"
                    }
            ]
    }
    

相关问题