search

Home  >  Q&A  >  body text

mongodb内嵌文档查找和修改问题

数据的格式是这样的:

{
    "_id" : 1,
    "people_id" : 1,
    "albums" : [
        {
            "id" : 1,
            "name" : "123",
            "privilege" : 0,
        },
        {
            "id" : 2,
            "name" : "Q",
            "privilege" : 5,
        },
        {
            "id" : 3,
            "name" : "Q",
            "privilege" : 5,
        },
    ]
}

{
    "_id" : 2,
    "people_id" : 2,
    "albums" : [
        {
            "id" : 1,
            "name" : "4",
            "privilege" : 0,
        },
        {
            "id" : 2,
            "name" : "5",
            "privilege" : 0,
        }
    ]
}

现在我想的是
1 , 查询people_id 为 1 且 privilege 为 5的内嵌文档,mongodb的查询命令怎么写的啊

2,更新people_id 为 2 且权限为 id为2的内嵌文档的name字段值为 6,更新命令怎么写的啊

查询我用
db.find({"people_id" : 1,"albums":{"$elemMatch" : {"privilege" : 5}}})
来尝试匹配过,但是匹配出了:

{
    "_id" : 1,
    "people_id" : 1,
    "albums" : [
        {
            "id" : 1,
            "name" : "123",
            "privilege" : 0,
        },
        {
            "id" : 2,
            "name" : "Q",
            "privilege" : 5,
        },
        {
            "id" : 3,
            "name" : "Q",
            "privilege" : 5,
        },
    ]
}

我并不想要id为1的那个,只想唯一匹配id为2和3那个

修改,我确实不会,
还请大家帮忙提下解决方法,非常谢谢咯!

ringa_leeringa_lee2796 days ago1217

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-24 09:14:57

    The query statement can be simplified as follows:

    db.demo.find({"people_id" : 1, "albums.privilege": 5})
    

    The query results return documents that meet the matching conditions. Although the returned fields can be mapped, it really cannot only return the documents you mentioned id为2和3. But now that you have obtained the json document that meets the conditions, you can write a program to obtain the desired embedded subdocument.

    The update statement is as follows:

    db.demo.update({people_id:2, "albums.id":2}, { $set : {"albums.$.name":6 }})
    

    It just updates the first matching subdocument in the array, but albums.idit seems to be unique and should meet your needs.

    reply
    0
  • 迷茫

    迷茫2017-04-24 09:14:57

    There is a solution for #1. $elemMatch can also be used as the second parameter of the find method to limit the elements in the returned array. As follows:

    db.demo.find({"albums.privilege":5, people_id:1}, {"albums":{$elemMatch:{privilege:5}}})
    

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-24 09:14:57

    Is your subdocument ID incremented by itself?

    reply
    0
  • Cancelreply