Mongodb:查询嵌套在数组中的json对象 [英] Mongodb: Query a json-object nested in an array

查看:237
本文介绍了Mongodb:查询嵌套在数组中的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm quite new to mongodb and there is one thing I can't solve right now:
Let's pretend, you have the following document (simplified):

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

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

Which query would return the json-object, in which the value equals 'value2'?

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

That means, i need this json-object:

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

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

Of course I already tried a lot of possible queries, but none of them returned the right, e.g.

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

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

Can someone help and show me, what I'm doing wrong?
Thanks!

推荐答案

使用位置操作符

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

这篇关于Mongodb:查询嵌套在数组中的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆