我有两个收藏
-
User
{
"_id" : ObjectId("584aac38686860d502929b8b"),
"name" : "John"
}
-
Role
{
"_id" : ObjectId("584aaca6686860d502929b8d"),
"role" : "Admin",
"userId" : "584aac38686860d502929b8b"
}
我想加入这些集合基于userId (in role收藏) -_id ( in user收藏)。
我尝试了以下查询:
db.role.aggregate({
"$lookup": {
"from": "user",
"localField": "userId",
"foreignField": "_id",
"as": "output"
}
})
只要我将 userId 存储为 ObjectId,这就会给我预期的结果。当我的 userId 是字符串时,没有结果。
PS:我试过了
外域字段: '_id'.valueOf()
and
外域字段:'_id'.toString()
。但没有运气基于 ObjectId 字符串字段进行匹配/连接。
任何帮助将不胜感激。
您可以使用$toObjectId https://docs.mongodb.com/manual/reference/operator/aggregation/toObjectId/来自 mongodb 的聚合4.0它转换字符串id
to ObjectId
db.role.aggregate([
{ "$lookup": {
"from": "user",
"let": { "userId": "$_id" },
"pipeline": [
{ "$addFields": { "userId": { "$toObjectId": "$userId" }}},
{ "$match": { "$expr": { "$eq": [ "$userId", "$$userId" ] } } }
],
"as": "output"
}}
])
或者你可以使用$toString https://docs.mongodb.com/manual/reference/operator/aggregation/toString/来自 mongodb 的聚合4.0哪个转换ObjectId
to String
db.role.aggregate([
{ "$addFields": { "userId": { "$toString": "$_id" }}},
{ "$lookup": {
"from": "user",
"localField": "userId",
"foreignField": "userId",
"as": "output"
}}
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)