gpt4 book ai didi

java - 根据多个条件从 mongodb 检索所有匹配记录

转载 作者:行者123 更新时间:2023-11-30 08:01:55 25 4
gpt4 key购买 nike

我的 mongodb 集合架构采用以下格式

    { 
"_id" : 1,
"sid" : 11,
"shapes" : [
{"shape" : "square", "color" : "red"},
{"shape" : "circle", "color" : "green"},
{"shape" : "rectangle", "color" : "green"},
......,
......,
{"shape" : "elipse", "color" : "green"}
]
},
........,
........,
{
"_id" : 100
"sid" : 111,
"shapes" : [
{"shape" : "square", "color" : "red"},
{"shape" : "circle", "color" : "green"},

......,
{"shape" : "rectangle", "color" : "green"}
]
}

我想使用 java 驱动程序从中检索 sid = 11形状如 %r% 的记录。我使用了以下代码,但它只给了我第一条记录,请建议我做错了什么?

            DBObject query = new BasicDBObject("sid", 1);
DBObject searchQuery = new BasicDBObject();
Pattern regex = Pattern.compile(".*r.*");
searchQuery.put("shape", regex);
DBObject elemMatchQuery = new BasicDBObject("$elemMatch", searchQuery);

DBObject fields = new BasicDBObject();
fields.put("shapes", elemMatchQuery);

DBCursor cursor = collection.find(query, fields);
System.out.println(cursor.count());
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

最佳答案

使用 mongo aggregation 查询如下:

db.collectionName.aggregate({"$match":{"sid":11}},{"$unwind":"$shapes"},{"$match":{"shapes.shape":{"$regex":".r."}}})

和等效的java代码:

    BasicDBObject match = new BasicDBObject("sid",11);
BasicDBObject firstmatchObj = new BasicDBObject();
firstmatchObj.put("$match", match);
BasicDBObject unwind = new BasicDBObject("$unwind","$shapes");
BasicDBObject matchAfterUnwind = new BasicDBObject("shapes.shape",new BasicDBObject("$regex",".r."));
BasicDBObject secondmatchObj = new BasicDBObject();
secondmatchObj.put("$match", matchAfterUnwind);
List<DBObject> pipeline = new ArrayList<>();
pipeline.add(firstmatchObj);
pipeline.add(unwind);
pipeline.add(secondmatchObj);
AggregationOutput output = collection.aggregate(pipeline);
for (DBObject res : output.results()) {
System.out.println(res);
}

关于java - 根据多个条件从 mongodb 检索所有匹配记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31784765/

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