我有两个收藏
用户
{ "_id" : ObjectId("584aac38686860d502929b8b"), "name" : "John" }
角色
{ "_id" : ObjectId("584aaca6686860d502929b8d"), "role" : "Admin", "userId" : "584aac38686860d502929b8b" }
我想根据 userId(在 role 集合中)- _id(在 user 中加入这些集合> 收藏)。
我尝试了以下查询:
db.role.aggregate({
"$lookup": {
"from": "user",
"localField": "userId",
"foreignField": "_id",
"as": "output"
}
})
只要我将 userId 存储为 ObjectId,这就会给我预期的结果。当我的 userId 是字符串时,没有结果。 ps:我试过了
foreignField: '_id'.valueOf()
和
foreignField: '_id'.toString()
。但是根据 ObjectId 字符串字段匹配/加入没有运气。
任何帮助将不胜感激。
最佳答案
您可以使用 $toObjectId
来自 mongodb 4.0 的聚合,它将字符串 id
转换为 ObjectId
db.role.aggregate([
{ "$lookup": {
"from": "user",
"let": { "userId": "$_id" },
"pipeline": [
{ "$addFields": { "userId": { "$toObjectId": "$userId" }}},
{ "$match": { "$expr": { "$eq": [ "$userId", "$$userId" ] } } }
],
"as": "output"
}}
])
或者您可以使用 $toString
来自 mongodb 4.0 的聚合,它将 ObjectId
转换为 String
db.role.aggregate([
{ "$addFields": { "userId": { "$toString": "$_id" }}},
{ "$lookup": {
"from": "user",
"localField": "userId",
"foreignField": "userId",
"as": "output"
}}
])
关于Mongodb加入从String到ObjectId的_id字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41093647/