[英]Mongodb: Query a json-object nested in an array
我对mongodb很新,有一件事我现在无法解决:
让我们假装,你有以下文件(简化):
{
'someKey': 'someValue',
'array' : [
{'name' : 'test1',
'value': 'value1'
},
{'name' : 'test2',
'value': 'value2'
}
]
}
哪个查询将返回json-object,其中值等于'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'})
有人可以帮助并告诉我,我做错了什么?
谢谢!
使用Positional运算符
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"}
尝试这样的$ in运算符:
db.test.find({"array.value" : { $in : ["value2"]}})
您可以在元素匹配中传递多个查找对象以获得确切的答案。
db.test.find({'array':{$elemMatch:{value:"value2"}})
output: {'name' : 'test1','value': 'value1'}
使用$ elemMatch和dot(。)来获取所需的输出
db.getCollection('mobiledashboards').find({"_id": ObjectId("58c7da2adaa8d031ea699fff") },{ viewData: { $elemMatch : { "widgetData.widget.title" : "England" }}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.