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

1784 views javascript

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.

{_id:110, "miles" : 7567,"service" : "Wipers replacement"}

{_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


Try this:

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

More info here:

posted this

Have an answer?


Please login first before posting an answer.