简体   繁体   中英

How do I update an an array, within an object, within an array?

I'm currently working with the Node.js MongoDB driver, and am faced with a structure that is as follows:

users (database)
users (collection)  
    {           
        name: bob,
        data: [         
            {                   
                name: mydata,
                relations: [ ** I want to addToSet here! ** ]                   
            },              
            {                   
                name: mydata2,
                relations: []                   
            }           
        ]           
    },      
    {           
        name: jeff,
        data: [...same stuff...]            
    }

So, I have an array, that is within an object, that is within an array, and my aim to add an entry to it.

I realize that this looks like a relational thing that MongoDB is poorly suited for, but I am trying to accommodate some relational data that may be uploaded. Does anyone happen to know a way to do this? Not necessarily in one query, just in any way at all.

As noted in the comments by TeTeT, you can do this by using the $ positional update operator in conjunction with $addToSet . In the shell:

db.users.update(
    {name: 'bob', 'data.name': 'mydata'}, 
    {$addToSet: {'data.$.relations': 'add me'}})

The $ identifies the element in the data array that was matched in the query conditions.

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