如何通过参考字段将一个集合的字段值设置为另一个集合的字段值?

时间:2016-01-25 22:25:38

标签: mongodb mongodb-query nosql

MongoDB的:

假设我的收藏品A包含字段[_id, foo],而B包含字段[_id, refId, bar]

对于A.foo

的每个匹配记录,我想将B.bar设置为B._refId == A._id

在关系数据库中,这将通过JOIN进行简单的更新。

在MongoDB中,似乎我必须获取所有A和B,并遍历它们并在每次传递时调用比较和更新函数。这似乎非常低效。有没有更好的办法?

基本上,我希望找到比以下更好的方法:

A.find().forEach(function setFooToBar(anA){
    //find the matching B.bar value for anA, and update anA
    //seems terribly inefficient
});

1 个答案:

答案 0 :(得分:0)

假设您使用的是MongoDB的最新版本,则应该能够利用$ lookup。

链接:https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#example

示例:

db.a.aggregate([
{
  $lookup:
    {
      from: "b",
      localField: "bar",
      foreignField: "foo",
      as: "foobar"
    }
} 
])

希望这有帮助!

相关问题