gpt4 book ai didi

arrays - Mongodb:查询嵌套在数组中的json对象

转载 作者:IT老高 更新时间:2023-10-28 13:18:28 30 4
gpt4 key购买 nike

我对 mongodb 还很陌生,有一件事我现在无法解决:
假设,您有以下文件(简化版):

{
'someKey': 'someValue',
'array' : [
{'name' : 'test1',
'value': 'value1'
},
{'name' : 'test2',
'value': 'value2'
}
]
}

哪个查询会返回 json-object,其中 value 等于 'value2'?

也就是说,我需要这个 json 对象:

{
'name' : 'test2',
'value': 'value2'
}

当然,我已经尝试了很多可能的查询,但没有一个返回正确的,例如

db.test.find({'array.value':'value2'})
db.test.find({'array.value':'value2'}, {'array.value':1})
db.test.find({'array.value':'value2'}, {'array.value':'value2'})

有人可以帮我看看我做错了什么吗?
谢谢!

最佳答案

使用位置运算符

db.test.find(
{ "array.value": "value2" },
{ "array.$": 1, _id : 0 }
)

输出

{ "array" : [ { "name" : "test2", "value" : "value2" } ] }

使用聚合

db.test.aggregate([
{ $unwind : "$array"},
{ $match : {"array.value" : "value2"}},
{ $project : { _id : 0, array : 1}}
])

输出

{ "array" : { "name" : "test2", "value" : "value2" } }

使用 Java 驱动程序

    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
DB db = mongoClient.getDB("mydb");
DBCollection collection = db.getCollection("test");

DBObject unwind = new BasicDBObject("$unwind", "$array");
DBObject match = new BasicDBObject("$match", new BasicDBObject(
"array.value", "value2"));
DBObject project = new BasicDBObject("$project", new BasicDBObject(
"_id", 0).append("array", 1));

List<DBObject> pipeline = Arrays.asList(unwind, match, project);
AggregationOutput output = collection.aggregate(pipeline);

Iterable<DBObject> results = output.results();

for (DBObject result : results) {
System.out.println(result.get("array"));
}

输出

{ "name" : "test2" , "value" : "value2"}

关于arrays - Mongodb:查询嵌套在数组中的json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24294273/

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