gpt4 book ai didi

java - MongoDB3.0查询到java的转换

转载 作者:行者123 更新时间:2023-12-01 10:03:21 27 4
gpt4 key购买 nike

我正在研究 java 和 MongoDb 3.0,并且有一个查询,我想将其转换为 java 代码。

Mongo DB查询如下:

db.users.find({ $or: [ { updated_at:{ $gt:90, $lte:200}}, { updated_at:{ $gt:350, $lte:400}}, { updated_at:{ $gt:560, $lte:700}} ] })

Java 查询如下所示。

List<Document> orqueryList = new ArrayList<Document>();
List<String> list1 = new ArrayList<String>();
list1.add("90:200");
list1.add("350:400");
list1.add("560:700");

Document greaterQuery = new Document();
Document lessQuery = new Document();
Document lEQuery = new Document();
Document gEQuery = new Document();

for (String time : list1) {

String[] updatedAtt = tim.split(":");


gEQuery.put("$gte", Long.parseLong(updatedAtt[0]));
lEQuery.put("$lte", Long.parseLong(updatedAtt[1]));


greaterQuery.put("updated_at", gEQuery);
lessQuery.put("updated_at", lEQuery);
orqueryList.add(greaterQuery);
orqueryList.add(lessQuery);

}
query.put("$or", orqueryList);

但这不起作用,因为我的 orqueryList 列表给了我大小 3,最后的值如下

[Document{{received_at_server=Document{{$gte=560}}}}, Document{{received_at_server=Document{{$lte=700}}}}, Document{{received_at_server=Document{{$gte=560}}}}, Document{{received_at_server=Document{{$lte=700}}}}, Document{{received_at_server=Document{{$gte=560}}}}, Document{{received_at_server=Document{{$lte=700}}}}]

最佳答案

db.users.find({ $or: [ { updated_at:{ $gt:90, $lte:200}}, { updated_at:{ $gt:350, $lte:400}}, { updated_at:{ $gt:560, $lte:700}} ] })

查询分为两部分 -1.updated_at值$gt和$lte的AND运算2. 上述AND运算列表的OR运算。

    greaterQuery.put("updated_at", gEQuery);
lessQuery.put("updated_at", lEQuery);
orqueryList.add(greaterQuery);
orqueryList.add(lessQuery);

}
query.put("$or", orqueryList);

上面的java代码仅检查OR条件(列表或queryList)。您正在将 $gt 和 $lte 条件添加到 OR 条件本身。

尝试以下逻辑:

Document query = new Document();
List<String> list1 = new ArrayList<String>();
List<Document> andQueryList = new ArrayList<Document>();
list1.add("90:200");
list1.add("350:400");
list1.add("560:700");

for (String time : list1) {
String[] updatedAtt = time.split(":");

andQueryList.add(new Document("$and", Arrays.asList(new Document("updated_at", new Document("$gte", Long.parseLong(updatedAtt[0]))),
new Document("updated_at", new Document("$lte", Long.parseLong(updatedAtt[1]))))));
}
query.put("$or", andQueryList);

查询输出如下(相当于Mongo Query)

Document{{$or=[Document{{$and=[Document{{updated_at=Document{{$gte=90}}}}, Document{{updated_at=Document{{$lte=200}}}}]}}, Document{{$and=[Document{{updated_at=Document{{$gte=350}}}}, Document{{updated_at=Document{{$lte=400}}}}]}}, Document{{$and=[Document{{updated_at=Document{{$gte=560}}}}, Document{{updated_at=Document{{$lte=700}}}}]}}]}}

关于java - MongoDB3.0查询到java的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36640678/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com