Return partial array

Data
_id: "...", list: [ {w:"text1"}, {w:"text2"}, {w:"text3"}....]

with this query find({ list: {w: "text2" } }) this return the whole list, how can I return only matched documents?
expected: list: [{w:"text2"}]

You could use $filter aggregation pipeline operator to return a subset of an array that match the condition.

So, using your example, it would look like this:

db.partial.insert({ list: [{w:"text1"}, {w:"text2"}, {w:"text3"} ]   })

db.partial.aggregate([
    { $project: { list: {  $filter: { input: "$list", as: "item", cond: { $eq: [ "$$item.w", "text2" ]  }  }  } } }
]) 

Mahi

2 Likes