mongodb:给定键列表,检查集合中是否有与密钥匹配的文档

发布于 2025-01-25 12:04:59 字数 736 浏览 2 评论 0原文

假设我在用户集合中有以下数据:

    {
        "_id": "1",
        "name": "Robert"
    },
    {
        "_id": "2",
        "name": "David"
    },
    {
        "_id": "3",
        "name": "Sam"
    },
    {
        "_id": "4",
        "name": "Michael"
    }

以及给定的密钥列表:[“ 1”,“ 3”,“ 5”,“ 7”]

我期望的是检查每个键是否在集合中具有匹配的文档。因此,结果就是这样:

    {
        "_id": "1",
        "matched": true
    },
    {
        "_id": "3",
        "matched": true
    },
    {
        "_id": "5",
        "matched": false
    },
    {
        "_id": "7",
        "matched": false
    }

如何使用单个查询来实现此结果?感谢任何帮助,谢谢。

Let's say I have the following data in the User collection:

    {
        "_id": "1",
        "name": "Robert"
    },
    {
        "_id": "2",
        "name": "David"
    },
    {
        "_id": "3",
        "name": "Sam"
    },
    {
        "_id": "4",
        "name": "Michael"
    }

And a given list of keys: ["1", "3", "5", "7"]

What I expect is a check for each key whether it has a matched document in the collection. So the result would be like this:

    {
        "_id": "1",
        "matched": true
    },
    {
        "_id": "3",
        "matched": true
    },
    {
        "_id": "5",
        "matched": false
    },
    {
        "_id": "7",
        "matched": false
    }

How do I achieve this result using a single query? I would appreciate any helps, thanks.

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

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

发布评论

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

评论(1

指尖上得阳光 2025-02-01 12:04:59

该解决方案需要在用户集合中至少存在1个文档,

您可以通过使用$ Untind使用给定的_id s创建文档。然后执行$查找并检查结果数组的大小。

db.User.aggregate([
  {
    $limit: 1
  },
  {
    $project: {
      _id: [
        "1",
        "3",
        "5",
        "7"
      ]
    }
  },
  {
    "$unwind": "$_id"
  },
  {
    "$lookup": {
      "from": "User",
      "localField": "_id",
      "foreignField": "_id",
      "as": "userLookup"
    }
  },
  {
    "$project": {
      matched: {
        $gt: [
          {
            $size: "$userLookup"
          },
          0
        ]
      }
    }
  }
])

这是 mongo playground 供您参考。

This solution requires at least 1 document exists in the User collection

You can create the documents with your given _ids by using $unwind. Then perform a $lookup and check for the size of result array.

db.User.aggregate([
  {
    $limit: 1
  },
  {
    $project: {
      _id: [
        "1",
        "3",
        "5",
        "7"
      ]
    }
  },
  {
    "$unwind": "$_id"
  },
  {
    "$lookup": {
      "from": "User",
      "localField": "_id",
      "foreignField": "_id",
      "as": "userLookup"
    }
  },
  {
    "$project": {
      matched: {
        $gt: [
          {
            $size: "$userLookup"
          },
          0
        ]
      }
    }
  }
])

Here is the Mongo playground for your reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文