要从另一个文档中过滤文档,您需要使用填充字段。
为此,我们使用聚合。在查找中;我们将 cars 字段与 user 字段连接起来,以达到用户字段的值,如用户名等。
在 MongoDB Compass 中,您需要使用页面左下角的
mongosh
。首先,
需要实现您想要进行过滤的数据库。为此;
use arpaslanOto
现在,您切换了数据库。当前分贝是
alparslanOto
。然后在字段中写下您要搜索的过滤器;
db.cars.aggregate([
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "UserCarTable",
},
},
{
$match: { "UserCarTable.username": username },
},
]);
希望对你有用
db.cars.aggregate([
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "cars",
},
},
{
$match: { "cars.name": "Mustafa" },
},
])
工作!!