java mongo 批量更新_如何在Java中使用MongoDB执行批量更新文件

使用示例手册中的新

{ "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 },

{ "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 },

{ "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }

以下characters集合执行多个操作:

Mongo shell:

try {

db.characters.bulkWrite([

{

insertOne:{

"document":{

"_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4

}

}

},

{

insertOne:{

"document": {

"_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3

}

}

},

{

updateOne: {

"filter" : { "char" : "Eldon" },

"update" : { $set : { "status" : "Critical Injury" } }

}

},

{

deleteOne: { "filter" : { "char" : "Brisbane"} }

},

{

replaceOne: {

"filter" : { "char" : "Meldane" },

"replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }

}

}

]);

}

catch (e) { print(e); }

它打印输出:

{

"acknowledged" : true,

"deletedCount" : 1,

"insertedCount" : 2,

"matchedCount" : 2,

"upsertedCount" : 0,

"insertedIds" : {

"0" : 4,

"1" : 5

},

"upsertedIds" : {

}

}

相应的Java 3.2实现如下:

MongoCollection collection = db.getCollection("characters");

List> writes = new ArrayList>();

writes.add(

new InsertOneModel(

new Document("_id", 4)

.append("char", "Dithras")

.append("class", "barbarian")

.append("lvl", 3)

)

);

writes.add(

new InsertOneModel(

new Document("_id", 5)

.append("char", "Taeln")

.append("class", "fighter")

.append("lvl", 4)

)

);

writes.add(

new UpdateOneModel(

new Document("char", "Eldon"), // filter

new Document("$set", new Document("status", "Critical Injury")) // update

)

);

writes.add(new DeleteOneModel(new Document("char", "Brisbane")));

writes.add(

new ReplaceOneModel(

new Document("char", "Meldane"),

new Document("char", "Tanys")

.append("class", "oracle")

.append("lvl", 4)

)

);

BulkWriteResult bulkWriteResult = collection.bulkWrite(writes);

对于你的问题使用

MongoCollection collection = db.getCollection("collection");

List> writes = Arrays.>asList(

new ReplaceOneModel(

new Document("_id", 1001), // filter

new Document("author", "newName"), // update

new UpdateOptions().upsert(true) // options

)

);

BulkWriteResult bulkWriteResult = collection.bulkWrite(writes);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值