Mongodb 将 _id 字段从 String 加入到 ObjectId [英] Mongodb Join on _id field from String to ObjectId
问题描述
我有两个收藏
用户
<代码>{"_id" : ObjectId("584aac38686860d502929b8b"),姓名":约翰"}
角色
<代码>{"_id" : ObjectId("584aaca6686860d502929b8d"),"角色": "管理员",用户 ID":584aac38686860d502929b8b"}
我想根据 userId(在 role 集合中) - _id(在 user> 收藏).
我尝试了以下查询:
db.role.aggregate({$查找":{"来自": "用户","localField": "userId","foreignField": "_id",作为":输出"}})
只要我将 userId 存储为 ObjectId,这就会给我预期的结果.当我的 userId 是一个字符串时,没有结果.Ps:我试过了
<块引用>外来字段:'_id'.valueOf()
和
<块引用>外来字段:'_id'.toString()
.但是没有运气匹配/加入基于 ObjectId 字符串字段.
任何帮助将不胜感激.
从 MongoDB 3.4 开始,这是不可能的.此功能已被请求,但尚未实现.以下是相应的门票:
现在您必须将 userId 存储为 ObjectId
<小时>编辑
以前的票在 MongoDB 4.0 中已修复.您现在可以使用以下查询实现此目的:
db.user.aggregate([{$项目":{_ID": {"$toString": "$_id"}}},{$查找":{"from": "角色","localField": "_id","foreignField": "userId",作为":角色"}}])
结果:
<预><代码>[{"_id": "584aac38686860d502929b8b",角色": [{"_id": ObjectId("584aaca6686860d502929b8d"),"角色": "管理员",用户 ID":584aac38686860d502929b8b"}]}]在线试用:mongoplayground.net/p/JoLPVIb1OLS
I have two collections
User
{ "_id" : ObjectId("584aac38686860d502929b8b"), "name" : "John" }
Role
{ "_id" : ObjectId("584aaca6686860d502929b8d"), "role" : "Admin", "userId" : "584aac38686860d502929b8b" }
I want to join these collection based on the userId (in role collection) - _id ( in user collection).
I tried the below query:
db.role.aggregate({
"$lookup": {
"from": "user",
"localField": "userId",
"foreignField": "_id",
"as": "output"
}
})
This gives me expected results as long as i store userId as a ObjectId. When my userId is a string there are no results. Ps: I tried
foreignField: '_id'.valueOf()
and
foreignField: '_id'.toString()
. But no luck to match/join based on a ObjectId-string fields.
Any help will be appreciated.
This is not possible as of MongoDB 3.4. This feature has already been requested, but hasn't been implemented yet. Here are the corresponding tickets:
- SERVER-22781: Allow $lookup between ObjectId (_id.str) and string
- SERVER-24947: Need a type conversion mechanism for booleans, ISODates, ObjectID
For now you'll have to store userId as ObjectId
EDIT
The previous tickets were fixed in MongoDB 4.0. You can now achieve this with the folowing query:
db.user.aggregate([
{
"$project": {
"_id": {
"$toString": "$_id"
}
}
},
{
"$lookup": {
"from": "role",
"localField": "_id",
"foreignField": "userId",
"as": "role"
}
}
])
result:
[
{
"_id": "584aac38686860d502929b8b",
"role": [
{
"_id": ObjectId("584aaca6686860d502929b8d"),
"role": "Admin",
"userId": "584aac38686860d502929b8b"
}
]
}
]
try it online: mongoplayground.net/p/JoLPVIb1OLS
这篇关于Mongodb 将 _id 字段从 String 加入到 ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!