我希望在使用mongoose 的用户之间实现完美匹配.

下面是一个模式示例:

username: "Nicolas",
fruitiwant:["apple", "orange"]
fruitihave: ["banana"]

我希望有一个json,可以显示完美匹配的用户.User A想要user B拥有的水果.User B wants那水果user A has.

谢谢你的回答.

推荐答案

我们可以使用$lookup匹配集合中满足条件的所有用户,然后我们只需分组以消除重复配对,如下所示:

db.collection.aggregate([
  {
    $lookup: {
      from: "collection",
      let: {
        ihave: "$bookihave",
        iwant: "$fruitiwant",
        id: "$_id"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $ne: [
                    "$_id",
                    "$$id"
                  ]
                },
                {
                  $gt: [
                    {
                      $size: {
                        "$setIntersection": [
                          "$$ihave",
                          "$fruitiwant"
                        ]
                      }
                    },
                    0
                  ]
                },
                {
                  $gt: [
                    {
                      $size: {
                        "$setIntersection": [
                          "$$iwant",
                          "$bookihave"
                        ]
                      }
                    },
                    0
                  ]
                }
              ]
            }
          }
        },
        {
          $project: {
            username: 1,
            
          }
        }
      ],
      as: "perfect"
    }
  },
  {
    $unwind: "$perfect"
  },
  {
    $project: {
      matchedUserNames: {
        $cond: [
          {
            $gt: [
              "$username",
              "$perfect.username"
            ]
          },
          [
            "$perfect.username",
            "$username",
            
          ],
          [
            "$username",
            "$perfect.username"
          ]
        ]
      }
    }
  },
  {
    $group: {
      _id: "$matchedUserNames"
    }
  }
])

Mongo Playground

Node.js相关问答推荐

node 模块错误:类型参数OT具有循环约束''

Twilio-获取呼叫录音不起作用的请求

EJS ForEach循环标记

使用 Google Drive API 按文件夹 ID 检索文件夹的内容

PM2 是否需要成为其托管项目的依赖项?

try 使用 pdf.js 时 pdf.getPage 不是函数

处理 UTC 日期和future

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

为什么我的 npm 脚本中的 glob 不起作用?

npm chokidar 触发事件两次

如何刷新 youtube-data-api v3 的访问令牌

Mongoose,如何一次更新多个?

Azure Function 在 2022 年 4 月 26 日禁用将用户字段设置为 HTTP 请求对象

如何申请在NextJS上下载文件的许可?

yarn.lock 和 npm 的 package-lock 有什么区别?

Node JS:自动 Select `http.get`与`https.get`

node.js(ES6 / Babel)中 import X 和 import * as X 的区别?

如何使用 Node.js 在服务器端管理多个 JS 文件

在浏览器中打开来自 Electron 的链接