简体   繁体   中英

Mongodb - How to update a nested Array

I have to update an Array nested in another Array. Is it possible to do that with the $addtoset operator?

Here is my document. I have a library wich has an Array of authors who have an Array of Books.

In this exemple, i'd like to add a new category to the book id 1 of the author id 1

How can i do that ?

{
    "id" : NumberLong(666),
    "library" : [ 
        {
            "id" : NumberLong(8888),
            "author" : [ 
                {
                    "id" : NumberLong(1),
                    "books" : [ 
                        {
                "id":1,
                            "title" : "plop",
                            "category" : ["horror"],
                            "isbn" : 12345
                        }, 
                        {
                "id":2,
                            "title" : "plup",
                            "category" : ["comics"],
                            "isbn" : 6789
                        }
                    ]
                }, 
                {
                    "id" : NumberLong(2),
                    "books" : [ 
                        {
                "id":3,
                            "title" : "blop",
                            "category" : ["horror"],
                            "isbn" : 96325
                        }, 
                        {
                "id":4,
                            "title" : "blup",
                            "category" : ["comics"],
                            "isbn" : 74125
                        }
                    ]
                }
            ]
        }
    ]
}

I tried this :

db.library.update(
    {"id":666,"author.id":1,"books.id":1},
    {"$addToSet": {"author.$.books.category": "humour" }}
)

But it doesn't works

How does it works ?

thanks a lot

    db.library.update(
       {"id":666,"library.author.id":1,"library.author.books.id":1},
      {"$addToSet": {"library.0.author.0.books.$.category": "Book"}}
     )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM