I'm struggling with writing a mongo script for my app to retrieve and display the service logs for a specific vehicle. In this case, I have two users, each with multiple vehicles that have their own set of service logs. Despite my efforts, I haven't been successful in only displaying the serviceLogs
entries from the second user with _id:"2"
for the vehicle
with _id:14
. Below is a snippet of 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've attempted without much success.
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 output:
{
"_id" : 111.0,
"miles" : 2134.0,
"service" : "Brake pads replacement"
},
{
"_id" : 112.0,
"miles" : 5678.0,
"service" : "VSS replacement"
}
If you have any suggestions or solutions, they would be greatly appreciated. Thank you.