9

我想将颜色从用户集合复制到汽车集合。我正在使用一个外键,即用户 ID。

> 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" }

谢谢你的帮助 !

4

2 回答 2

6

您的测试设置存在几个问题:

  • 字段名称的大小写不匹配(您是在引用color而不是Color在复制时)
  • 目标集合中只有一个示例外键匹配:ObjectId('515f7db83f71d6bcb1c41a48')
  • 您的更新只会影响“外键”的第一个匹配文档。这对于 1:1 的关系很好,但不是 1:many

考虑到上述情况的更正示例(除了不匹配的键):

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}示例文档中设置唯一实际匹配的外键:

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")
}
于 2013-04-08T02:08:44.910 回答
4

这是我的两分钱:你可以放弃“function(x)”。我更喜欢以下语法:

db.source_collection_name.find().forEach(
  doc=>
      db.target_collection_name.update(
        {"_id": doc._id},
        {$set: {"field_to_update": doc.field}}
      )
)

在你的情况下,这样的事情应该有效:

db.test1.User.find().forEach(
  doc=> 
    db.test2.Car.update( 
      { "userID": doc._id }, 
      { $set: { "color": doc.Color} } 
    ) 
);
于 2019-02-12T12:38:44.597 回答