如何使用java代码转换mongodb查询

如何使用java代码转换mongodb查询,mongodb,mongodb-java,Mongodb,Mongodb Java,我是MongoDB的新手。我想将这个mongo DB查询转换为java代码。我试过一点。但我有个问题。拜托,如果有人帮忙的话,那对我来说是个很大的帮助。提前谢谢 db.getCollection('test').aggregate( [{ $match:{ “ids”:999999, $or:[{“tags.name”:“roja”},{“tags.location”:“US”},{“tags.year”:2019}] } }, { “$facet”:{ 元数据:[{$count:“总计”}],

我是MongoDB的新手。我想将这个mongo DB查询转换为java代码。我试过一点。但我有个问题。拜托,如果有人帮忙的话,那对我来说是个很大的帮助。提前谢谢

db.getCollection('test').aggregate(
[{
$match:{
“ids”:999999,
$or:[{“tags.name”:“roja”},{“tags.location”:“US”},{“tags.year”:2019}]
}
},
{
“$facet”:{
元数据:[{$count:“总计”}],
数据:[{
$addFields:{
“重量”:{
$map:{
输入:“$tags”,
如:“tagsEl”,
在:{
“$add”:
[              
{$cond:[{$eq:['$$tagsEl.roja','roja']},15,1]},
{$cond:[{$eq:['$$tagsEl.location','US']},10,1]},
{$cond:[{$eq:['$$tagsEl.year',2019]},5,1]}
]
}
}
}
}
},{$skip:0},{$limit:10},{'$sort':{'weight':-1}]
}
}
]
)
您可以使用直接将查询转换为java代码,除非您不熟悉语法

//获取数据库
MongoDatabase db=mongoClient.getDatabase(“testdb”);
//收集
MongoCollection testCol=db.getCollection(“测试”);
//准备聚合管道阶段的列表。
List aggs=new ArrayList();
//您编写的每个管道阶段都使用js。等效的java语法是。。。
//对于{key1:value1,key2:value2}
新文档().追加(“键1”、“值1”).追加(“键2”、“值2”)
//对于像[“abc”,1,{key3,value3}]这样的数组
数组.asList(“abc”,1,新文档(“key3”,“value3”))
//例如,脚本的一部分可以用java实现,如下所示。
加总(
新文档(“$match”,//匹配聚合管道阶段
新文件(“ids”,999999)
.append(“$or”,Arrays.asList)(
新文件(“标签名称”、“roja”),
新文件(“标签、位置”、“美国”),
新文件(“标签年份”,2019年)
))
)
);
//您可以根据需要向aggs列表添加任意多个阶段。
//执行
MongoCursor=testCol.aggregate(aggs.iterator();
while(cursor.hasNext()){
文档d=游标.next();
//做你的手术。
}
//Get database
MongoDatabase db = mongoClient.getDatabase("testdb");

//get collection
MongoCollection<Document> testCol = db.getCollection("test");

//prepare a list of aggregation pipeline stages.
List<Bson> aggs = new ArrayList<>();

//each pipeline stage you wrote is in js. the equivalent java syntax is...

//for {key1:value1,key2:value2}
  new Document().append("key1","value1").append("key2","value2")

//for array such as ["abc",1,{key3,value3}]
  Arrays.asList("abc",1,new Document("key3","value3"))


//for example , part of your script can be implemented in java as below.
 aggs.add(
  new Document("$match",//match aggregation pipeline stage
    new Document("ids",9999999)
      .append("$or",Arrays.asList(
        new Document("tags.name","roja"),
        new Document("tags.location","US"),
        new Document("tags.year",2019)
       ))
  )
);
//you can add as many stages as you need to aggs list.
//execute
MongoCursor<Document> cursor = testCol.aggregate(aggs).iterator();
while(cursor.hasNext()){
  Document d = cursor.next();
  //do your operation.
}