首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用NodeJS的MongoDB complex $graphlookup

使用NodeJS的MongoDB complex $graphlookup
EN

Stack Overflow用户
提问于 2018-03-07 22:32:59
回答 1查看 609关注 0票数 0

我正在写一个NodeJS程序,我遇到了障碍。对于编写复杂的MongoDB查询,我还是个新手,据我所知,MongoDB的NodeJS实现还没有包含'createView()‘函数,这使得这项工作更具挑战性。下面是我的数据库的结构和示例数据:

代码语言:javascript
复制
-------------------------------
_id | username | friends(array)
-------------------------------
  1 |   user1  |    [user2]
  2 |   user2  | [user1, user3]
  3 |   user4  |    [user3]

我正在尝试编写一个查询来检查user1的朋友是否与user2的朋友相等。(在这个场景中,我只想返回一个只包含‘user3’的数组)

我在解决这个问题上遇到了一些困难,因为我不能使用视图,并且必须使用一个包含的查询来执行所有这些逻辑。我知道mongo有一些可能对解决方案有用的函数,比如$graphlookup,但我在使用它们时一无所获。

如果有人感兴趣,这是我到目前为止得到的:

代码语言:javascript
复制
// Query1 this creates a view that 
// contains all usernames of friends of user4

db.createView(
  'userView',
  collection, [{
    $match: {
      username: user4
    }
  }, {
    $unwind: "$friends"
  }, {
    $group: {
      _id: "$friends"
    }
  }, {
    $project: {
      _id: 1
    }
  }]
);

代码语言:javascript
复制
// Query2 this creates a view that
// contains all usernames of friends of friends of user1

db.createView(
  'friendsView',
  collection, [{
    $match: {
      username: {
        $in: user1FriendsArray
      }
    }
  }, {
    $unwind: "$friends"
  }, {
    $group: {
      _id: "$friends"
    }
  }, {
    $project: {
      _id: 1
    }
  }]
);

代码语言:javascript
复制
// Query3 (this is incorrect) this query should find 
// any matches between the two views and return them within an array

db.collection.aggregate([{
  $group: {
    _id: {
      $and: [userView.$_id, friendsView.$_id]
    },
    count: {
      $sum: 1
    }
  }
}, {
  $match: {
    count: 2
  }
}, {
  $project: {
    _id: 1
  }
}]);

我相信将会有一种方法来执行所有这一切是一个单一的查询,然而,我有一个完整的噩梦计算出这个查询可能是什么。

任何帮助都将非常感谢<3

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49154403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档