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

Jon*_* M. 8 arrays json find mongodb

我对mongodb很新,有一件事我现在无法解决:
让我们假装,你有以下文件(简化):

{
   'someKey': 'someValue',
   'array'  : [
       {'name' :  'test1',
        'value':  'value1'
       },
       {'name' :  'test2',
        'value':  'value2'
       }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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

这意味着,我需要这个json对象:

{
    'name' :  'test2',
    'value':  'value2'
}
Run Code Online (Sandbox Code Playgroud)

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

db.test.find({'array.value':'value2'})
db.test.find({'array.value':'value2'}, {'array.value':1})
db.test.find({'array.value':'value2'}, {'array.value':'value2'})  
Run Code Online (Sandbox Code Playgroud)

有人可以帮助并告诉我,我做错了什么?
谢谢!

Tus*_*hra 17

使用Positional运算符

db.test.find(
    { "array.value": "value2" },
    { "array.$": 1, _id : 0 }
)
Run Code Online (Sandbox Code Playgroud)

产量

{ "array" : [ { "name" : "test2", "value" : "value2" } ] }
Run Code Online (Sandbox Code Playgroud)

使用聚合

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

产量

{ "array" : { "name" : "test2", "value" : "value2" } }
Run Code Online (Sandbox Code Playgroud)

使用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"));
    }
Run Code Online (Sandbox Code Playgroud)

产量

{ "name" : "test2" , "value" : "value2"}
Run Code Online (Sandbox Code Playgroud)