Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return $sample result as appended JSON key MongoDB

I perform a query to find one specific record by ID in MongoDB. It works fine, and returns me the following document:

{
   key1: "value1",
   key2: "value2"
}

Now I need to add to the returned JSON record the key "seeAlso".

This key will contain a sample of 3 other records in the same collection.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The final document should look like it:

{
   key1: "value1",
   key2: "value2",
   seeAlso: [
      {doc1},
      {doc2},
      {doc3},
   ]
}

The $sample I already know how to do. Gotta add the following to the pipeline:

  {
    '$sample': {
      'size': 10
    }
  }

What I don’t know yet is how to store the result of this sample in the "seeAlso" key. Such key needs to be created at this point, it doesn’t yet exist.

>Solution :

You may just need to do the $sample in a subpipeline. To leave out the original record, add a $match at the start of the subpipeline to leave out by _id

db.collection.aggregate([
  {
    "$match": {
      key1: "value1"
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "let": {
        id: "$_id"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $ne: [
                "$_id",
                "$$id"
              ]
            }
          }
        },
        {
          "$sample": {
            "size": 3
          }
        }
      ],
      "as": "seeAlso"
    }
  }
])

Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading