search

Home  >  Q&A  >  body text

请教:mongodb帖子类表设计

1.帖子有内容有回复,如果在mongodb里只用1个表的话,可以设计成这样

{
    title:'巴拉巴拉',
    content:'巴拉巴拉',
    comments:[
        {
            user:123,//用户123的回复
            content:'123'
        },
        {
            user:456,//用户456的回复
            content:'456'
        }
    ]
}

这样的设计的话,如何修改 user:456 里的content?

1)是否用类似数组下标的方式?如:comments[1].content?如何写?
天蓬老师天蓬老师2839 days ago613

reply all(1)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-02 09:23:46

    If you already know the subscript of {user: 456}, you can change it using array subscript:

    db.coll.update({...}, {$set: {"comments.1.content": "567"}})

    Or according to the query conditions:

    db.coll.update({"comments.user": 456}, {$set: {"comments.$.content": 567}})

    where $ represents the matched array element. But this way will only modify the first matching array element. So be careful that your conditions must exactly match the element you want to change. Taking your data as an example, if this user has commented twice, there will be a problem with writing like this.

    reply
    0
  • Cancelreply