mongodb 数据更新疑问?

mongodb 如何更新comments中指定_id的replys数组(添加和删除)?

{
    "_id" : ObjectId("595111698cce5d034f60ae79"),
    "title" : "Flower ribbon H skirt",
    "desc" : "간딘스키 작품같은 느낌의 플라워 프린팅\n\n앞면은 랩 스커트 느낌이 연출되고\n뒷면은 밴딩으로 되어 있어\n66사이즈이신 분까지 착용가능한데요\n",
    "createTime" : "Mon Jun 26 2017 21:51:37 GMT+0800 (CST)",
    "comments" : [
        {
            "_id" : ObjectId("5959f338c465d90f75d8544d"),
            "comment" : "qeqweqwe",
            "replys" : [ ],
            "createTime" : ISODate("2017-07-03T07:33:12.072Z")
        },
        {
            "_id" : ObjectId("5959f756034ffb103ea3bf41"),
            "comment" : "qweqweq",
            "replys" : [ ],
            "createTime" : ISODate("2017-07-03T07:50:46.642Z")
        }
    ]
}
阅读 3.2k
2 个回答

想不出来能直接操作文档的办法,因为不知道要操作的 comment 在数组中的位置。

可以先找到这个 doc,拿到对象,然后对 comments 进行操作(纯 JavaScript),再去更新文档。

也可以考虑把 comments 分表存放,操起来更容易。

这样写,你看是否符合你的要求
源数据

db.getCollection('test2').insert([
{"comments" : [
    {
        "_id" : ObjectId("1111159632caf59808934724"),
        "comment" : "qeqweqwe",
        "replys" : [ ],
        "createTime" : ISODate("2017-07-03T07:33:12.072Z")
    },
    {
        "_id" : ObjectId("3333359632caf59808934724"),
        "comment" : "qweqweq",
        "replys" : [ ],
        "createTime" : ISODate("2017-07-03T07:50:46.642Z")
    }
]},
 {"comments" : [
    {
        "_id" : ObjectId("5959f338c465d90f75d8544d"),
        "comment" : "qeqweqwe",
        "replys" : [ ],
        "createTime" : ISODate("2017-07-03T07:33:12.072Z")
    },
    {
        "_id" : ObjectId("5959f756034ffb103ea3bf41"),
        "comment" : "qweqweq",
        "replys" : [ ],
        "createTime" : ISODate("2017-07-03T07:50:46.642Z")
    }
]},
   
    ])

根据 id 插入指定数据

db.getCollection('test2').update({'comments._id': ObjectId("5959f338c465d90f75d8544d")}, { $push: { 'comments.$.replys':'pdd'} })

根据 id 删除指定数据

db.getCollection('test2').update({'comments._id': ObjectId("5959f338c465d90f75d8544d")}, { $pull : { 'comments.$.replys':'pdd'} })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题