1

I am having following mongo query which is executed in mongo shell.

db.test.update({ 
uuid: "160597270101684", 
sessionId: "160597270101684.1" 
}, { 
$setOnInsert: {
  stamps: {
    currentVisit: "1377500985", 
    lastVisit: "1377500985"
  }
},
$push:{
  visits: {
    page: "google.com",
    method: "GET"
  }
}
}, { upsert:true })

Because i am new to java, I am little bit confused to create the basicDBObject.

I had tried like this for sample

BasicDBObject doc = new BasicDBObject("uuid",1).append("session",2);
BasicDBObject upsertion = new BasicDBObject("upsert",true);
collection.update(doc,upsertion);

But its not working.

Any help will be great.

1 Answer 1

3

The upsert option isn't specified with a DBObject but with a third argument to DBCollection.update

public WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi)

You'll need to form a DBObject for update by appending $setOnInsert, $push, stamps and visits.

BasicDBObject update = new BasicDBObject();
BasicDBObject stamps = new BasicDBObject();
stamps.append("currentVisit", "1377500985").append("lastVisit", "1377500985");
BasicDBObject visits = new BasicDBObject();
update.append("$setOnInsert", stamps).append("$push", visits);

collection.update(doc, update, true);
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.