gpt4 book ai didi

java - 如何从 mongo 中找到选定的数组元素

转载 作者:行者123 更新时间:2023-12-01 22:18:28 25 4
gpt4 key购买 nike

我只想从 mongo 文档中查找选定的数组元素。就像在以下文档中我只想从数组返回困难问题。我正在使用 java 的 mongo 驱动程序。

BasicDBObject query=new BasicDBObject("questionList.type", "hard");
DBCursor curssc = collection.find(query);

文档

{
"testpaperid": 1,
"testpaperNo": "science",
"questionList":
[
{
"question": "this is question no 1",
"type": "hard"
},
{
"question": "this is question no 2",
"type":"simple"
},
{
"question": "this is question no 3",
"type": "hard"
}
]
}

最佳答案

如果使用 $elemMatch运算符它限制 <array> 的内容查询结果中的字段仅包含与 $elemMatch 匹配的第一个元素情况。

因此,如果您运行此查询:

db.collectionName.find({"questionList":{"$elemMatch":{"type":"hard"}}},{"questionList.type.$":1})

与上面查询等效的java代码如下:

BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("type", "hard");
BasicDBObject elemMatchQuery = new BasicDBObject();
elemMatchQuery.put("$elemMatch", eleMatch);
BasicDBObject query = new BasicDBObject();
query.put("questionList", elemMatchQuery);
BasicDBObject projection = new BasicDBObject();
projection.put("questionList.type.$", 1);
DBCollection dbcoll = mongoTemplate.getCollection("collectionName");
DBObject object = dbcoll.find(query, projection);

这仅返回第一个匹配的 type:hard输出包含 "questionList" : [ { "question" : "this is question no 1", "type" : "hard" } ]并非全部questionList包含 type:hard 的数组

为了避免这种情况,应该使用 mongo java aggregation driver和 mongo 聚合查询如下所示:

db.collectionName.aggregate({
"$unwind": "$questionList"
}, {
"$match": {
"questionList.type": "hard"
}
}, {
"$group": {
"_id": "$_id",
"testpaperid": {
"$first": "$testpaperid"
},
"testpaperNo": {
"$first": "$testpaperNo"
},
"questionList": {
"$push": "$questionList"
}
}
}).pretty()

java 中的聚合查询如下:

// unwind  questionList
DBObject unwind = new BasicDBObject("$unwind", "$questionList");
// create pipeline operations, with the $match
DBObject match = new BasicDBObject("$match", new BasicDBObject("questionList.type", "hard"));
// Now the $group operation
DBObject groupFields = new BasicDBObject("_id", "$group field");
groupFields.put("testpaperid", new BasicDBObject("$first", "$testpaperid"));
groupFields.put("testpaperNo", new BasicDBObject("$first", "$testpaperNo"));
groupFields.put("questionList", new BasicDBObject("$push", "$questionList"));
DBObject group = new BasicDBObject("$group", groupFields);
// run aggregation
List < DBObject > pipeline = Arrays.asList(unwind, match, group);
AggregationOutput output = collectionName.aggregate(pipeline);
for(DBObject result: output.results()) {
System.out.println(result);
}

关于java - 如何从 mongo 中找到选定的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467152/

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