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

20

我对mongodb还不是很熟悉,现在有一件事情我无法解决:
假设你有以下简化的文档:

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

哪个查询会返回值等于'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'})  

有人能帮忙并展示我,我做错了什么吗?
谢谢!

4个回答

30

使用定位符操作符

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"}

我该如何检索与匹配的嵌套字段一起获取一些父级字段呢? 我希望在响应中得到类似于这样的内容: {'someKey': 'someValue','array' : [{ "name": "test2" , "value": "value2"}]} - hitesh kaushik

1
你可以在元素匹配中传递多个查找对象以获得精确答案。
db.test.find({'array':{$elemMatch:{value:"value2"}})

output: {'name' :  'test1','value':  'value1'}

1

尝试使用$in操作符,像这样:

db.test.find({"array.value" : { $in : ["value2"]}})


谢谢你的帮助,但不幸的是它还是不起作用。如果我在终端中运行它,它会返回整个文档。 - Jonas M.

0

使用 $elemMatch 和点(.)来获取您所需的输出

db.getCollection('mobiledashboards').find({"_id": ObjectId("58c7da2adaa8d031ea699fff") },{ viewData: { $elemMatch : { "widgetData.widget.title" : "England" }}})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接