问题描述
尽管我在stackOverFlow
Although i have found a similar question on stackOverFlow MongoDB copy a field to another collection with a foreign key
我想将字段name
从userdetails
集合复制到user
集合,其中userDetails中的userId等于user中的_id.
I want to copy a field name
from userdetails
collection to user
collection where userId in userDetails equals _id in user.
用户集合
{
"_id" : ObjectId("5b97743bbff66e0be66283cc"),
"username" : "mmi_superadmin",
"accId" : "acc1"
}
{
"_id" : "c21d580ea3ca5c7a1664bd5feb57f0c8",
"username" : "client",
"accId" : "acc1"
}
userDetail 集合
{
"_id" : ObjectId("5b97743bbff66e0be66283cd"),
"userId" : "5b97743bbff66e0be66283cc",
"name" : "mmi_superadmin"
}
{
"_id" : "5bab8a60ef86bf90f1795c44",
"userId" : "c21d580ea3ca5c7a1664bd5feb57f0c8",
"name" : "RAHUL KUMAR TIWARI"
}
这是我的查询:
db.userDetails.find().forEach(
function(x) {
db.user.update( {_id :x.userId}, {$set: {name:x.name}});
}
);
此查询部分有效.它仅更新_id为字符串类型的user
文档. _id为ObjectId的用户文档不会更新.
This query is partially working. It only updates user
documents where _id is of type string. User document with _id as ObjectId are not getting updated.
推荐答案
请检查您的文档_id(因为在您的示例中某些_id不是有效的文档_id,例如c21d580ea3ca5c7a1664bd5feb57f0c8
不是mongo _id),并使用以下查询:
Please check your documents _id's (because in your example some _id's is not valid documents _id's. for example c21d580ea3ca5c7a1664bd5feb57f0c8
not a mongo _id) and use this query:
let usersIds = [];
db.user.find({"_id": {$type: 7}}).forEach(doc => {
usersIds.push(doc._id + '')
db.userDetail.find({
userId: {
$in: usersIds
}
}).forEach(doc => {
db.user.update(
{
"_id": ObjectId(doc.userId)
},
{
$set: {
"name": doc.name
}
},
{
multi: false,
upsert: false
}
)
})
})
如果您有任何疑问,请随时提问
if you have any question feel free to ask
这篇关于将外键作为混合类型将一个字段从一个集合复制到mongodb中的另一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!