Run native mongodb query with mongodb java driver

南笙酒味 提交于 2021-01-27 07:37:05

问题


I want to execute CRUD operations with java likeupdateOne(),updateMany() or deleteMany() etc. But when I want to run with operators like $set, $unset I have to import new classes like Updates or create nested Document objects. I want to insert JSON query as native Mongodb uses. Ex: myCollection.updateOne(Json_String_filter,Query_with_operoters_like_$set_as_Json_string);


回答1:


Use Document.parse(String json) from org.bson.Document. It returns Document object. Here is an example from Official MongoDb tutorial.

Original:

{
     $set: { "size.uom": "cm", status: "P" },
     $currentDate: { lastModified: true }
   }

You can run in java as:

collection.updateMany(new Document(),Document.parse("{\n" +
                "     $set: { \"size.uom\": \"cm\", status: \"P\" },\n" +
                "     $currentDate: { lastModified: true }\n" +
                "   }"));


来源:https://stackoverflow.com/questions/50535193/run-native-mongodb-query-with-mongodb-java-driver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!