$push and $set in same MongoDB update
Asked Answered
I

3

38

I'm trying to use MongoDB's Java driver to make two updates ($set and $push) to a record in the same operation. I'm using code similar to the following:

    BasicDBObject pushUpdate = new BasicDBObject().append("$push", new BasicDBObject().append("values", dboVital));
    BasicDBObject setUpdate = new BasicDBObject().append("$set", new BasicDBObject().append("endTime", time));
    BasicDBList combinedUpdate = new BasicDBList();
    combinedUpdate.add( pushUpdate);        
    combinedUpdate.add( setUpdate);


    collection.update( new BasicDBObject().append("_id", pageId), combinedUpdate, true, false);

When I combine the $set and $push into the same update via a BasicDBList, I get an IllegalArgumentException: "fields stored in the db can't start with '$' (Bad Key: '$push')".

If I make two separate updates, both pushUpdate and setUpdate produce valid results.

Thanks!

Impetuous answered 30/1, 2012 at 21:41 Comment(0)
N
60

I don't know Java driver, but do you have to create a list there? What happens if you try this code?

BasicDBObject update = new BasicDBObject().append("$push", new BasicDBObject().append("values", dboVital));
update = update.append("$set", new BasicDBObject().append("endTime", time));

collection.update( new BasicDBObject().append("_id", pageId), update, true, false);

This should produce the equivalent of

db.collection.update({_id: pageId}, {$push: {values: dboVital}, $set: {endTime: time}});

Whereas your code produces (I suspect) this:

db.collection.update({_id: pageId}, [{$push: {values: dboVital}}, {$set: {endTime: time}}]);
Needlecraft answered 30/1, 2012 at 21:45 Comment(0)
T
0

BasicDBObject update = new BasicDBObject().append("$push", new BasicDBObject().append("values", dboVital)); update = update.append("$set", new BasicDBObject().append("endTime", time));

collection.update( new BasicDBObject().append("_id", pageId), update, true, false);

Tented answered 20/9, 2022 at 9:38 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Belligerence
H
-1

My mongodb version is 3.4.20 and while using

db.collection.update({_id: pageId}, [{$push: {values: dboVital}}, {$set: {endTime: time}}]);

I received error

[thread1] Error: field names cannot start with $ [$push] :

To solve that error we can use:

db.collection.update({_id: pageId}, {$push: {values: dboVital}, $set: {endTime: time}});
Haustellum answered 2/7, 2019 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.