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"
2

1 Answer 1

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}}
])
Sign up to request clarification or add additional context in comments.

1 Comment

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 :: stackoverflow.com/questions/3985214/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.