1

I have a collection with data that looks sort of like this

{
  "part": [
    { "a": "1", "b": "a" },
    { "a": "23", "b": "b" },
    { "a": "4", "b": "c" },
  ]
}

What I would like is a way of searching for documents where the join of all a parts equals the search that I am looking for.

for example 1234 should match the document above, but 124 should not.

is this possible with MongoDB?

2 Answers 2

2

You can do it with Aggregation framework:

  • $match with $eq - To filter only documents where concatenated a properties of part array are equal to the input string.
  • $reduce with $concat - To concatenate all a properties of part array for each document.
db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          "1234",
          {
            "$reduce": {
              "input": "$part",
              "initialValue": "",
              "in": {
                "$concat": [
                  "$$value",
                  "$$this.a"
                ]
              }
            }
          }
        ]
      }
    }
  }
])

Working example

Sign up to request clarification or add additional context in comments.

Comments

1

You can use aggregate with $reduce to join string then $match to filter your string.
Here is the playground.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.