MongoDB 使用外键将字段复制到另一个集合 [英] MongoDB copy a field to another collection with a foreign key
本文介绍了MongoDB 使用外键将字段复制到另一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将颜色从用户集合复制到汽车集合.我使用的外键是 userID.
I want to copy over the color from user collection to the Car collection. I'm using a foreign key which is userID.
> db.test1.User.find()
{ "_id" : ObjectId("515f7db83f71d6bcb1c41a48"), "age" : 33, "Color" : "blue" }
{ "_id" : ObjectId("515f7dc03f71d6bcb1c41a49"), "age" : 52, "Color" : "red" }
{ "_id" : ObjectId("515f7dc43f71d6bcb1c41a4a"), "age" : 43, "Color" : "yellow" }
> db.test2.Car.find()
{ "_id" : ObjectId("515f84883f71d6bcb1c41a54"), "speed" : 291, "userID" : ObjectId("515f7db83f71d6bcb1c41a48") }
{ "_id" : ObjectId("515f84883f71d6bcb1c41a55"), "speed" : 202, "userID" : ObjectId("515f7db83f71d6bcb1c41a49") }
{ "_id" : ObjectId("515f84883f71d6bcb1c41a56"), "speed" : 193, "userID" : ObjectId("515f7db83f71d6bcb1c41a4a") }
这是我的查询
db.test1.User.find().forEach(
function(x)
{
db.test2.Car.update( { userID: x._id }, { $set: { color: x.color} } )
} );
我想要这个结果:
> db.test2.Car.find()
{ "_id" : ObjectId("515f84883f71d6bcb1c41a54"), "speed" : 291, "userID" : ObjectId("515f7db83f71d6bcb1c41a48"), "color" : "blue" }
{ "_id" : ObjectId("515f84883f71d6bcb1c41a55"), "speed" : 202, "userID" : ObjectId("515f7db83f71d6bcb1c41a49"), "color" : "red" }
{ "_id" : ObjectId("515f84883f71d6bcb1c41a56"), "speed" : 193, "userID" : ObjectId("515f7db83f71d6bcb1c41a4a"), "color" : "yellow" }
感谢您的帮助!
推荐答案
您的测试设置存在几个问题:
There are several issues with your test set up:
- 字段名称大小写不匹配(复制时引用的是
color
而不是Color
) - 目标集合中只有一个示例外键匹配:
ObjectId('515f7db83f71d6bcb1c41a48')
- 您的更新只会影响外键"的第一个匹配文档.这对于 1:1 的关系很好,但不是 1:many
考虑到上述情况的更正示例(除了不匹配的键):
A corrected example taking the above into account (aside from the non-matching keys):
db.test1.User.find().forEach(
function(x) {
db.test2.Car.update(
// query
{ userID: x._id },
// update
{ $set: { color: x.Color} },
// options:
{ "multi" : true } // Update all matching documents
);
}
);
这导致为示例文档中实际匹配的唯一外键设置 {color:blue}
:
Which results in setting {color:blue}
for the only foreign key that actually matches in the sample documents:
db.test2.Car.find()
{
"_id" : ObjectId("515f84883f71d6bcb1c41a55"),
"speed" : 202,
"userID" : ObjectId("515f7db83f71d6bcb1c41a49")
}
{
"_id" : ObjectId("515f84883f71d6bcb1c41a56"),
"speed" : 193,
"userID" : ObjectId("515f7db83f71d6bcb1c41a4a")
}
{
"_id" : ObjectId("515f84883f71d6bcb1c41a54"),
"color" : "blue",
"speed" : 291,
"userID" : ObjectId("515f7db83f71d6bcb1c41a48")
}
这篇关于MongoDB 使用外键将字段复制到另一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文