MongoDB查找具有反向匹配的记录

发布于 2025-02-12 15:54:29 字数 399 浏览 1 评论 0原文

我有以下结构可以存储用户的类似。例如,_id1用户喜欢用户_id2& _id3。 _id1用户仅与用户_id2匹配。

我只需要匹配记录。

文档结构 -

  [
  {'来自':'_ id1','to':'_ ID2'},
  {'来自':'_ id1','to':'_ id3'},
  {'来自':'_ id2','to':'_ ID1'},
这是给出的
 

预期输出 -

  [
  {'来自':'_ id1','to':'_ ID2'},
  {'来自':'_ id2','to':'_ ID1'},
这是给出的
 

I have the following structure to store user's like. For example, _id1 user likes user _id2 & _id3. Where the _id1 user is having a match with user _id2 only.

I need only records with a match.

Document Structure --

[
  {'from':'_id1', 'to':'_id2'},
  {'from':'_id1', 'to':'_id3'},
  {'from':'_id2', 'to':'_id1'},
]

Expected Output --

[
  {'from':'_id1', 'to':'_id2'},
  {'from':'_id2', 'to':'_id1'},
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜中书 2025-02-19 15:54:29

您可以在“夫妇”上$ group,然后匹配那些被总结为2的。我只是用$ cond做到的,​​然后创建元组[_id1,_id2],其中较小的ID总是首先是这样,例如:

db.collection.aggregate([
  {
    $group: {
      _id: {
        $cond: [
          {
            $gt: [
              "$from",
              "$to"
            ]
          },
          [
            "$to",
            "$from"
          ],
          [
            "$from",
            "$to"
          ]
        ]
      },
      sum: {
        $sum: 1
      },
      roots: {
        $push: "$ROOT"
      }
    }
  },
  {
    $match: {
      sum: {
        $gt: 1
      }
    }
  },
  {
    $unwind: "$roots"
  },
  {
    $replaceRoot: {
      newRoot: "$roots"
    }
  }
])

You can $group on the "couple" and only then match those that were summed to be 2. The trick is to make sure the _id your grouping on is the same - I just did it with $cond and create the tuple [ _id1, _id2 ] where the smaller id is always first, like so:

db.collection.aggregate([
  {
    $group: {
      _id: {
        $cond: [
          {
            $gt: [
              "$from",
              "$to"
            ]
          },
          [
            "$to",
            "$from"
          ],
          [
            "$from",
            "$to"
          ]
        ]
      },
      sum: {
        $sum: 1
      },
      roots: {
        $push: "$ROOT"
      }
    }
  },
  {
    $match: {
      sum: {
        $gt: 1
      }
    }
  },
  {
    $unwind: "$roots"
  },
  {
    $replaceRoot: {
      newRoot: "$roots"
    }
  }
])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文