我有两个 Mongo 模式:
用户:
{
_id: ObjectId,
name: String,
country: ObjectId // Reference to schema Country
}
国家:
{
_id: ObjectId,
name: String
}
我想获取所有国家名称为“VietNam”的用户。
对于这种情况,我可以使用哪种查询(仅限用户架构)?
我希望它看起来像这个 SQL 查询:
SELECT *
FROM User
JOIN Country
ON User.country = Country._id
WHERE Country.name = 'VietNam'
最佳答案
您可以在 mongodb 3.6 及更高版本中使用以下聚合
db.country.aggregate([
{ "$match": { "name": "VietNam" } },
{ "$lookup": {
"from": Users.collection.name,
"let": { "countryId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$country", "$$countryId" ] } } },
],
"as": "users",
}},
{ "$unwind": "$users" },
{ "$replaceRoot": { "newRoot": "$users" }}
])
关于javascript - 如何在 MongoDB 中按引用字段查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54642073/