How do I find and display a specific object from an array in MongoDB?

1784 views javascript
3

In my app, I am having trouble writing a mongo script to find and display the service logs to one vehicle. For example, I have two users with multiple vehicles. Each vehicle has multiple service logs. With the queries I wrote, I'm not having much luck displaying only the serviceLogs objects from the second user with _id:"2" from the vehicle with _id:14. Below is the sample data.

db.collection.insert(
{_id:"1",vehicles:[
{_id:11,make:"Mazda",model:"CX5",serviceLogs:[
{_id:110, "miles" : 7567,"service" : "Wipers replacement"}
]}]});

db.collection.insert(
{_id:"2",vehicles:[
{_id:12,make:"Mazda",model:"CX5",serviceLogs:[]},
{_id:13,make:"Chevy",model:"Sonic",serviceLogs:[]},
{_id:14,make:"Toyota",model:"Tacoma",serviceLogs:[
{_id:111, "miles" : 2134,"service" : "Brake pads replacement"},
{_id:112, "miles" : 5678,"service" : "VSS replacement"}
]}]});

Below are the queries I tried, I've tinkered around with them but not getting any luck.

db.collection.find({"_id": "2", vehicles: {$elemMatch: {make: "Toyota", model: "Tacoma"}}} ).pretty();
db.collection.find({"_id": "2", "vehicles.$.serviceLogs": {$elemMatch: {serviceLogs:{id: 111}}}})
db.collection.find({"_id": "2", vehicles: {$elemMatch: {serviceLogs:{id: 111}}}})

Expected results:

{
  "_id" : 111.0,
  "miles" : 2134.0,
  "service" : "Brake pads replacement"
}, 
{
  "_id" : 112.0,
  "miles" : 5678.0,
  "service" : "VSS replacement"
}

Any suggestions would be greatly appreciated, thanks.

answered question

1 Answer

12

Try this:

db.collection.find({"_id": "2", vehicles: {$elemMatch: {make: "Toyota", model: "Tacoma"}}} ).project({serviceLogs: 1});

More info here: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

posted this

Have an answer?

JD

Please login first before posting an answer.