Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
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'?

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!

like image 809
Jonas M. Avatar asked Jun 18 '14 20:06

Jonas M.


People also ask

How do I access nested objects in MongoDB?

In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I access a nested object in JSON?

Accessing nested json objects is just like accessing nested arrays. Nested objects are the objects that are inside an another object. In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I find an element in an array in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }


1 Answers

Using Positional operator

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

    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"}
like image 165
Tushar Mishra Avatar answered Sep 18 '22 00:09

Tushar Mishra