Home > Enterprise >  MongoDB find join array
MongoDB find join array

Time:12-20

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related