I want to list cars by username, how can i do?
CodePudding user response:
For filtering documents from another document, you need to use populate the field.
For this, we are using aggregate. In lookup ; we are connect the cars field with user field to reach user field's values as username etc.
In MongoDB Compass, you need to use MONGOSH at the left bottom of the page. Firstly, need to achieve the database you want to make filter on. For this,
use arpaslanOto
Now, you switched your DB. Current db is alparslanOto. Then write the filters you want to search on the field as;
db.cars.aggregate([
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "UserCarTable",
},
},
{
$match: { "UserCarTable.username": username },
},
];
)
I hope, it's useful for you
CodePudding user response:
With the method you suggested, the response returns empty.
-Response from below codes
CodePudding user response:
db.cars.aggregate([
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "cars",
},
},
{
$match: { "cars.name": "Mustafa" },
},
])
Working!!