1

is it possible to return only matched elements within array that contains Accessories

input sample

[
{
  "values":[
     "Aerial and fa ade cables Accessories",
     "LANmark 5 Shielded Cable",
     "Market challenges"
  ],
  "doc":"doc1"
},
{
  "values":[
     "Aerial and fa ade cables ",
     "Tools Accessories"
  ],
  "doc":"doc2"
}
]

expected output

 "Aerial and fa ade cables Accessories",
 "Tools Accessories"
mohamed hamada
  • 289
  • 1
  • 13

1 Answers1

2

This snippet should work here:
Mongo v4.2.3

db.collection.aggregate([
   {$unwind: "$values"},
   {$match: { values: { $regex: /accessories/i } }},
   {$project:{values: 1, _id: 0}}
])
Basu_C
  • 380
  • 1
  • 5
  • You can do this & similarly equally you should not do this when your dataset is huge - So this definitely is not the best answer, `$unwind` will explode docs in collection, In your case you'll be working on 5 docs instead of just 2, which makes a query to run slow & also you need a `group` stage to merge docs if needed - which adds additional unnecessary stages !! There are a lot of questions on similar topic - Check this answer :: https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection – whoami - fakeFaceTrueSoul Mar 03 '20 at 15:36