How to insert created_timestamp in MongoDB using its Java Driver for Javascript

975 views Asked by At

I'm trying to use $setOnInsert using javascript, so I can insert the created_timestamp just the first time it hits Mongo.

var uri = new Packages.com.mongodb.MongoClientURI("mongodb://usr:pwd@localhost:27017/admin");
var mongoClient = new Packages.com.mongodb.MongoClient(uri);
var database = mongoClient.getDatabase("mydb");
var collection = database.getCollection("mycollection");
var curdate = DateUtil.getCurrentDate('yyyy-MM-dd');
var jsonDoc = JSON.stringify( 
    {       "unique_id": uid  //comes from a var from other part of the code
            "user" : {
            "id": id,
            "first": first,
            "last": last,   
            $setOnInsert: {"created_timestamp": curdate},
            "modified_timestamp": curdate
    }
);
var doc = Packages.org.bson.Document.parse(jsonDoc);
var comp = Packages.org.bson.Document.parse(JSON.stringify({"unique_id": idd}));
collection.replaceOne(comp, doc, (new com.mongodb.client.model.UpdateOptions().upsert(true)));  
mongoClient.close();

And I'm receiving always a message that says that $setOnInsert is an invalid BSON field. What should I do?

BTW, I'm doing this javascript in Mirth. And already have its JARs, they are working fine when I'm just inserting documents. But I've been having this problem when I want to create the timestamp.

UPDATE

When I'm trying to use updateOne(), instead of replaceOne() Mirth gives me this error:

LINE NUMBER: 2030 DETAILS: Wrapped java.lang.IllegalArgumentException: Invalid BSON field name unique_id

When using this line:

collection.updateOne(comp, doc, (new com.mongodb.client.model.UpdateOptions().upsert(true)));   
//line 2030

Even using Update, I don't know how should I use the setOnInsert function from this driver. Sincerelly, I'm not good when it comes to javascript.

1

There are 1 answers

4
dnickless On BEST ANSWER

To my knowledge, replaceOne() does not support $setOnInsert.

And am uncertain as to how the precise Mirth syntax should look like and I do not have an environment to try it out. However, in raw MongoDB syntax, what you want to get is something like this:

collection.update(
{
    "unique_id": idd
    // add any other field here that makes up your filter
},
{
    $set: { "unique_id": uid },
    $set: { "user": { "id": id, "first": first, "last": last } },
    // add any other field to set as part of the update
    $setOnInsert: {"created_timestamp": new Date()}
}, {
    upsert: true
})

I hope this helps a little.

Update:

I would suggest you try passing the following instance to your updateOne command as the second parameter:

Document doc = new Document("unique_id", uid)
                .append("user", new Document("first", first).append("last", last))
                .append("$setOnInsert", new Document("created_timestamp": curdate));