Home > front end >  MongoDB: Given a list of keys, check if there is any document in a collection that matches the key
MongoDB: Given a list of keys, check if there is any document in a collection that matches the key

Time:05-03

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.

CodePudding user response:

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.

  • Related