I
I
Ivan R2016-10-21 20:49:47
MongoDB
Ivan R, 2016-10-21 20:49:47

How to filter an array in a collection?

Hello everyone, I have a collection:

{
   "_id" : 2,
   "name" : "bob",
   "age" : 42,
   "mess" : [ { "text" : 'hi', "countT" : 8 }, { "text" : 'no', "countT" : 20 } ]
}
{
   "_id" : 3,
   "name" : "ahn",
   "age" : 22,
   "mess" : [ { "text" : 'no', "countT" : 8 }, { "text" : 'hi', "countT" : 8 }, { "text" : 'no', "countT" : 20 } ]
}
{
   "_id" : 6,
   "name" : "abc",
   "age" : 43,
   "mess" : [ { "text" : 'good', "countT" : 8 }, { "text" : 'no', "countT" : 20 }, { "text" : 'good', "countT" : 8 }, { "text" : 'no', "countT" : 20 } ]
}

I need to display from the element with "_id" = 6 all elements from the field "mess" where "mess.text" = 'good'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-12-02
@uAZ1k

If I understand you correctly, then I think this will work for you.

db.test.aggregate([{$match : {_id : 6}}, {$redact : {$cond : {if : {$eq : ["$text", "no"]}, then : '$$PRUNE', else : '$$DESCEND'}}}])
,
result :
{ "_id" : 6, "name" : "abc", "age" : 43, "mess" : [ { "text" : "good", "countT" : 8 }, { "text" : "good", "countT" : 8 } ] }
or so
result :
{ "mess" : [ { "text" : "good", "countT" : 8 }, { "text" : "good", "countT" : 8 } ] }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question