Reputation: 447
I need all my inserted/updated documents in MongoDb to have an auto-updated currentDate
So let's assume I have the following Json shipment object (which I'm getting from a 3rd party restful API) :
String jsonString = {"tracking_number": "123", "deliveryAddress": { "street_line_1": "12 8th St.", "city": "NY", "state": "NY" }, "cutomers": [ { "firstName": "John", "email": "[email protected]" }, { "firstName": "Alex", "email": "[email protected]" } ] }
Problem #1, I need to insert the object into the DB and set "currentDate", but insertOne does not work for me:
MongoClient mongo = new MongoClient(mongodb_host, mongodb_port);
MongoDatabase db = mongo.getDatabase("Test");
MongoCollection<Document> collection = db.getCollection("InsertOneExample");
Document doc = Document.parse(jsonString);
doc.append("lastModifiedTs", new BSONTimestamp());
collection.insertOne(doc);
System.out.println(doc);
This one does not populate "lastModifiedTs" as you can see below
Document{{tracking_number=123, deliveryAddress=Document{{street_line_1=12 8th St., city=NY, state=NY}}, cutomers=[Document{{firstName=John, [email protected]}}, Document{{firstName=Alex, [email protected]}}], lastModifiedTs=TS time:null inc:0, _id=5a6b88a66cafd010f1f2cffd}}
Problem #2
If I'm getting an update on my shipment, the tracking number is the same, but all the other fields may change.
The following code crashes:
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
options.returnDocument(ReturnDocument.AFTER);
options.upsert(true);
Bson update = Updates.combine(Document.parse(jsonString), Updates.currentTimestamp("lastModifiedTs"));
Document query = new Document("tracking_number", "123");
Document result = collection.findOneAndUpdate(query, update, options);
With the exception: "Invalid BSON field name equipmentShipmentAddress"
Notes: needless to say, I can perform several operations: (1) insert the object, get the "_id" field, (2) update the "lastModifiedTs" field (3) read the object by "_id" and get the updated "lastModifiedTs" value, but it's three operation where I expect to be able to achieve everything with a single operation
How can I achieve my goal elegantly?
Thanks
Upvotes: 0
Views: 1410
Reputation: 76004
Solution to Problem #1 - Insert new Date()
to provide new datetime.
Document doc = Document.parse(jsonString);
doc.append("lastModifiedTs", new Date());
collection.insertOne(doc);
Solution to Problem #2 - Use findOneAndReplace
FindOneAndReplaceOptions options = new FindOneAndReplaceOptions();
options.returnDocument(ReturnDocument.AFTER);
Document replace = Document.parse(jsonString);
replace.append("lastModifiedTs", new Date());
Document query = new Document("tracking_number", "123");
Document result = collection.findOneAndReplace(query, replace, options);
Upvotes: 1