$push and $set in same MongoDB update

后端 未结 2 605
粉色の甜心
粉色の甜心 2020-12-29 21:56

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:

         


        
相关标签:
2条回答
  • 2020-12-29 22:17

    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}});
    
    0 讨论(0)
  • 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}}]);
    
    0 讨论(0)
提交回复
热议问题