简体   繁体   English

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

[英]Mongodb: Query a json-object nested in an array

I'm quite new to mongodb and there is one thing I can't solve right now: 我对mongodb很新,有一件事我现在无法解决:
Let's pretend, you have the following document (simplified): 让我们假装,你有以下文件(简化):

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

Which query would return the json-object, in which the value equals 'value2'? 哪个查询将返回json-object,其中值等于'value2'?

That means, i need this json-object: 这意味着,我需要这个json对象:

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

Of course I already tried a lot of possible queries, but none of them returned the right, eg 当然我已经尝试了很多可能的查询,但没有一个返回正确的,例如

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! 谢谢!

Using Positional operator 使用Positional运算符

db.test.find(
    { "array.value": "value2" },
    { "array.$": 1, _id : 0 }
)

Output 产量

{ "array" : [ { "name" : "test2", "value" : "value2" } ] }

Using aggregation 使用聚合

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

output 产量

{ "array" : { "name" : "test2", "value" : "value2" } }

Using Java Driver 使用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"));
    }

output 产量

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

尝试这样的$ in运算符:

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

You can pass multiple find objects in element match for getting the exact answer. 您可以在元素匹配中传递多个查找对象以获得确切的答案。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM