Search code examples
mongodbmongodb-javanosql

How to find and merge mongodb document


I'm trying test application that should merge two documents with same key. I thought that findAndModify() will do a job, but it doesn't. For example, lets assume that there is a document in 'data' collection: { "Date":"2014-08-23", "field1":"A"}

I tried:

bo.put( "Date", "2014-08-23");
bo.put( "field2", "B" );
query.put( "Date", "2014-08-23" );

DBObject resObj = collection.findAndModify( query, bo );

The result is { "Date" : "2014-08-23", "field2" : "B" } And I want { "Date" : "2014-08-23", "field1":"A", "field2" : "B" }

How I can do it within one DB or Collection command?


Solution

  • By default, the normal update function (or its cousin findAndModify) completely replaces a document. When you want to retain the old content and only update some of its fields, you need to use the $set operator.

    In MongoDB shell syntax:

    db.collection.update(
         { "Date": "2014-08-23" },
         { "$set": { "field2": "B"} }
     );
    

    In Java syntax:

    DBObject where = new BasicDBObject("Date", "2014-08-23");
    DBObject update = new BasicDBObject("$set", new BasicDBObject("field2", "B"));
    collection.update(where, update);