Arrays Mongodb:查询嵌套在数组中的json对象
我是mongodb的新手,有一件事我现在无法解决:Arrays Mongodb:查询嵌套在数组中的json对象,arrays,json,mongodb,find,Arrays,Json,Mongodb,Find,我是mongodb的新手,有一件事我现在无法解决: 让我们假设您有以下文档(简化): 哪个查询将返回值等于“value2”的json对象 这意味着,我需要这个json对象: { 'name' : 'test2', 'value': 'value2' } 当然,我已经尝试了很多可能的查询,但是没有一个返回正确的结果 db.test.find({'array.value':'value2'}) db.test.find({'array.value':'value2'}, {'a
让我们假设您有以下文档(简化): 哪个查询将返回值等于“value2”的json对象 这意味着,我需要这个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'})
有人能帮我看看我做错了什么吗?谢谢 像这样尝试$in操作符:
db.test.find({“array.value”:{$in:[“value2”]})
使用位置运算符
db.test.find(
{ "array.value": "value2" },
{ "array.$": 1, _id : 0 }
)
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"));
}
输出
{ "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驱动程序
db.test.find(
{ "array.value": "value2" },
{ "array.$": 1, _id : 0 }
)
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"));
}
使用$elemMatch和点(.)获得所需的输出
db.getCollection('mobiledashboards').find({"_id": ObjectId("58c7da2adaa8d031ea699fff") },{ viewData: { $elemMatch : { "widgetData.widget.title" : "England" }}})
您可以在元素匹配中传递多个find对象以获得准确答案
db.test.find({'array':{$elemMatch:{value:"value2"}})
output: {'name' : 'test1','value': 'value1'}
谢谢你的帮助,但不幸的是它也不起作用。如果我在终端中运行它,它将返回整个文档