Reputation: 39
Is it possible to retrieve the specific value in an array of objects inside an another object in mongodb??
@Document
class vehicleStation {
@Id
String stationId;
List<car> cars;
}
@Document
class car{
@Id
String carNo;
String name;
}
And my json structure will look like below
{"_id":"0001","cars":[{"_id":"C001", "name":"Honda"},{"_id":"C002","name":"Ford"}]}
Is it possible retrieve the value of "name" for a particular vehicleStation (stationId="0001" and carNo="C002") which is "Ford"
how to query the mongodb to get the value "Ford" for vehicleStation (stationId="0001" and carNo="C002")
Upvotes: 2
Views: 128
Reputation: 754
Since you are doing an _id query at the top level this returns only one document. You can do
db.so.findOne({_id:"0001"},{cars:{$elemMatch:{"_id":"C002"}}}).cars[0]
to get the inner object or
db.so.findOne({_id:"0001"},{cars:{$elemMatch:{"_id":"C002"}}}).cars[0].name
to get only the name Note - If you have multiple subobjects with the _id as C002 this will only the first match as documented.
Upvotes: 2
Reputation: 754
You could do that using the $elemMatch projection operator. e.g. from the shell
> db.so.find({_id:"0001"},{cars:{$elemMatch:{"_id":"C002"}}})
{ "_id" : "0001", "cars" : [ { "_id" : "C002", "name" : "Ford" } ] }
Upvotes: 2