1

Disclaimer: Totally new in MongoDB.

I have a document structured something like this:

{
  "hd": [
    {
      "rd": [
        {
          "rm": [
            {
              "code": "a1asd"
            },
            {
              "code": "a24aer"
            }
          ]
        },
        {
          "rm": [
            {
              "code": "b16hwe7"
            },
            {
              "code": "b2z41s"
            }
          ]
        }
      ]
    }
  ]
}

And I want return the subdocument that only contains, for example, "a1". How will I approach this problem?

The solutions I tried so far looks something like this

db.foo.aggregate([
    {
        $match: {
            "hd.rd.rm.code": /a1/
        }
    },
    {
        $project: {
            "hd.rd": {
                $filter: {
                    input: "$hd.rd",
                    as: "roomData",
                    cond: {
                        $eq: [
                            {
                                $substr: [ "$$roomData.rm.code", 0, 10]
                            },
                            "a1"
                        ]
                    }
                }
            }
        }
    }
])

but the query above doesn't work. I found out $regexMatch doesn't work with $cond, so I'm quite loss at the moment.

My expected results will look something like this:

{
  "hd": {
    "rd": {
      "rm": {
        "code": "a1asd"
      }
    }
  }
}

1 Answer 1

1

This query will give you the desired result,

db.collection.aggregate([
 {
    "$unwind": "$hd"
  },
  {
    "$unwind": "$hd.rd"
  },
  {
    "$unwind": "$hd.rd.rm"
  },
  {
    "$match": {
      "hd.rd.rm.code": /a1/
    }
  }
])

ScreenShot of Mongo Instance enter image description here

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

5 Comments

what are you getting? I have tested the query and it gives me the correct result.
I tried it on my mongo instance, and it doesn't return any result even tho the nested document exist.
Are you replace the collection with your collection name and using the right database as default database is test in mongo instance.
@cankentcode I have added the screenshot of the query with result. Here i added your data in a collection b
confirmed it's working. there's an error on my part. thank you

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.