1

Need to get element of nested array by condition. Origin collection:

[
  {
    code: 134,
    bindings: [
      {
        devId: "71156ce8-ac2b-4282-9f5a-10133441057c",
        userIds: ["9d300b89-29c0-45a8-a4d3-019cfc8f1c7b"]
      },
      {
        devId: "ca33efa1-ec27-4ee1-8117-8b8ab29c1790",
        userIds: ["73e5af2f-fe01-41a3-bebd-6bab895cab58"]
      },
      {
        devId: "a03f5fbd-f279-4182-bfb6-33aba9de5751",
        userIds: ["dc0c5e59-ef1a-44b9-843b-a4ea73bbed2e"]
      }
    ]
  }
]

I try use aggregation function :

db.trigger.aggregate([
  { $match: { _id: "134" } },
  { $unwind: "$bindings" },
  { $match: { "bindings.devId": "ca33efa1-ec27-4ee1-8117-8b8ab29c1790" } },
  { $project: { _id: 0, dateset: 1 } },
  { $out: "bindings" }
]);

but it did not give the desired result. Сan someone tell me what i'm doing wrong?

2
  • 1
    Sample document has code set to 134 while in your query you're trying to match _id which is a string. Could you show us the desired result ? Commented May 21, 2019 at 11:51
  • desired result : { devId: "71156ce8-ac2b-4282-9f5a-10133441057c", userIds: ["9d300b89-29c0-45a8-a4d3-019cfc8f1c7b"] } element of array with specific devId Commented May 21, 2019 at 12:26

1 Answer 1

1

You can try below aggregation, $replaceRoot promotes nested document into root level:

db.collection.aggregate([
    {
        $match: { code: 134 }
    },
    {
        $unwind: "$bindings"
    },
    {
        $match: { "bindings.devId": "71156ce8-ac2b-4282-9f5a-10133441057c" }
    },
    {
        $replaceRoot: { newRoot: "$bindings" }
    }
])

Mongo Playground

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

1 Comment

Amazing. Thanks a lot!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.