0

I have a mongo pipeline. Here is the output of one of the steps.

    {
  "_id": "6249b7a8338c31b803a1e56b",
  "sentences": [
    66,
    61,
    98,
    44
  ],
  "documents": [
    {
      "sentences": [
        {
          "uuid": 66,
          "text": "cbElZuplrxPQicnBHvKQutEhZ",
          "index": 58,
          "cluster_id": "PyYvsHQfnypoowYsswiAJLlFP"
        },
        {
          "uuid": 61,
          "text": "cbElZuplrxPQicnBHvKQutEhZ",
          "index": 58,
          "cluster_id": "PyYvsHQfnypoowYsswiAJLlFP"
        }
      ]
    }
  ]
}

In one of the steps, I need to filter the array $documents.sentences based on whether the $documents.sentences.uuid is in $sentences. My pipeline $project stage is defined like this:

{
  "sentences": 1,
  "documents.sentences": {
    $filter: { 
      "input": "$documents.sentences", 
      "as": "s", 
      "cond": {
        $in: ["$$s.uuid", "$sentences"],
      }}
    
  }
}

However, this results in a completely empty $documents My question is, what is the best way to filter the documents.sentences array based on the condition, if documents.sentences.uuid is in sentences?

thank you for your time

1 Answer 1

1

As the sequences array is in an array of documents, you need to include an intermediary $map operation:

db.collection.aggregate([
  {
    "$project": {
      "sentences": 1,
      "documents": {
        $map: {
          "input": "$documents",
          "as": "d",
          "in": {
            "sequences": {
              $filter: {
                "input": "$$d.sentences",
                "as": "s",
                "cond": {
                  $in: [
                    "$$s.uuid",
                    "$sentences"
                  ],
                  
                }
              }
            }
          }
        }
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Adrien D. That is the correct answer, when I can accept, I will. Thank you so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.