1

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.

1
  • 1
    This mongoshell command might be useful: db.sample.update({'data.name': 'mydata'}, {$addToSet: {'data.$.relations': 4}}, true, true) Commented Jul 1, 2014 at 20:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.