0

I'm trying to get some objects of an array in mongodb.

I have something like this:

{
   _id: 1,
   prop1: "string",
   prop2: 4,
   prop3: [
       { val1: "a", val2: "b" },
       { val1: "c", val2: "d" },
       { val1: "a", val2: "l" },
       { val1: "b", val2: "m" },
       { val1: "j", val2: "k" },
       { val1: "a", val2: "o" }
}

And I want to get this result:

{
   _id: 1,
   prop1: "string",
   prop2: 4,
   prop3: [
       { val1: "a", val2: "b" },
       { val1: "a", val2: "l" },
       { val1: "a", val2: "o" }
}

As I know, $elemMatch only return the first matched element, and I would like to get all matched elemets.

I have read something about $redact (aggregation) here, but the only thing that I obtain are some errors.

develask
  • 3
  • 3

1 Answers1

0

i am supposing the name of your collection is data

  db.data.aggregate([
  {$match:{"prop3.val1":"a"}},
  {$group: {id:"$prop3"}}
  ])

I hope this could help you !!

mayank
  • 460
  • 3
  • 15