0

I am trying to update the following document in Mongodb.

    doc = { id : 10 , graph :[{userId:1,children:[2]},{userId:2,children:[]}]}

    db.test.insert(doc)

then I perform two updates:

db.test.update( {'id':10,'graph.userId' : 1}, { $push:{'graph.$.children':10}})

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph':{'userId':10,'children':[]}}})

(Saddly :

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph.$.children':10},$push:{'graph':{'userId':10,'children':[]}}})

does not work)

Is there a way to update these simultaneously ?

Thanks a lot

2 Answers 2

2

You can bundle multiple update operations together, but the only issue with what you've written in pseudo code is that the elements you're pushing belong to different arrays (graph and graph.children respectively.) This needs to be done in two pushes.

Try this:

db.test.update( { id:10, 'graph.userId':1 }, 
        { $push:{'graph.$.children' : 4 }, $push:{'graph' : {'userId':4,'children':[]}} } )
Sign up to request clarification or add additional context in comments.

2 Comments

really sorry but it turns out this does not work. I have edited the question, thanks
wont the second push override the first since they have the same key
1

The multiple keys in the modifier array stop it from working. You have to do two updates to do this if I read your shema right cos you are trying to push a new child onto the current position and push a new record into the subdocument of the parent.

The thing that stops it is the children[] setting. Mongo just does not know where to set that.

I suppose you could try:

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph.$.children':10},$pushAll:{'graph':{{'userId':10,'children':[]}}}})

But it is a long shot

1 Comment

thanks for your help, a pitty the simultneous update does not work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.