javascript - 如何使用 Javascript 的 Java 驱动程序在 MongoDB 中插入 created_timestamp

标签 javascript java mongodb mirth

我正在尝试通过 javascript 使用 $setOnInsert,因此我可以在它第一次访问 Mongo 时插入 created_timestamp。

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();

而且我总是收到一条消息,指出 $setOnInsert 是一个无效的 BSON 字段。我应该怎么办?

顺便说一句,我正在 Mirth 中执行此 javascript。并且已经有了它的 JAR,当我只是插入文档时它们工作正常。但是当我想创建时间戳时,我一直遇到这个问题。

更新

当我尝试使用 updateOne() 而不是 replaceOne() 时,Mirth 给我这个错误:

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

当使用这条线时:

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

即使使用更新,我也不知道如何使用此 driver 中的 setOnInsert 函数.真诚的,我不擅长 javascript。

最佳答案

据我所知,replaceOne() 不支持 $setOnInsert

我不确定 Mirth 的精确语法应该是什么样子,而且我没有环境来尝试它。然而,在原始的 MongoDB 语法中,你想要得到的是这样的:

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
})

希望对您有所帮助。

更新:

我建议您尝试将以下实例作为第二个参数传递给您的 updateOne 命令:

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

关于javascript - 如何使用 Javascript 的 Java 驱动程序在 MongoDB 中插入 created_timestamp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042187/

相关文章:

java - Windows 7 - System32 文件夹 - java.exe

java - 使用 Content-Type :application/json 时,对 Activiti REST API 的 POST 请求会导致 CORS 问题

java - 将类成员传递给方法

angular - 连接为 Meteor 客户端的 Ionic UI 的简单示例?

javascript - 在 JavaScript 中动态添加多个事件监听器

javascript - 未捕获的类型错误 : Cannot read property 'clientHeight' of null

javascript - 无法在 react.js 中使用本地镜像

javascript - 创建 'this' 的备份

python - Mongoengine:以 EmbededDocuments 作为值的动态字段

node.js - 在 Node 中检查付款状态的有效方法?