0

Say I have the following document

Item

{
    details: [
            {
                "title": "Name",
                "content": "",
                "is_private": false,
                "order": 0,
                "type": "text"
            },
            {
                "title": "Price",
                "content": "",
                "is_private": true,
                "order": 1,
                "type": "text"
            },
            {
                "title": "Company",
                "content": "",
                "is_private": false,
                "order": 2,
                "type": "text"
            }
        ],
}

If I wanted to return only the subdocument fields details which have is_private === false, is there a way to do it in mongoose's query or do I need to use aggregation?

e.g.

ItemModel
    .find()
    // something should go here to remove
A. L
  • 11,695
  • 23
  • 85
  • 163
  • not familiar with mongoose but can give you native mongo aggregation query – dsharew Aug 22 '18 at 06:20
  • @dsharew I wouldn't mind that either, in case someone doesn't answer. – A. L Aug 22 '18 at 06:21
  • You have to use `$filter` aggregation here... As you asked before https://stackoverflow.com/questions/51833317/how-to-filter-a-nested-lower-subdocument... Even if you use `$elemMatch` then it will only return the first matched document with `is_private === false` not all matching ones – Ashh Aug 22 '18 at 06:41
  • @AnthonyWinzlet yeah, was mainly just curious if there was a query for this in mongoose. – A. L Aug 22 '18 at 07:07
  • Well aggregation is also a query... So instead you should ask for "can it be done using find query"... Isn't it? – Ashh Aug 22 '18 at 07:12

1 Answers1

1

In case you wanted to do it using native aggregation query:

db.getCollection('item').aggregate([
   {
      $unwind:"$details"
   },
   {
      $match:{
         "details.is_private":true
      }
   },
   {
      $group:{
         _id:"$_id",
         details:{
            $push:"$details"
         }
      }
   }
])

Output:

{
    "_id" : ObjectId("5b7d0edb6cfaf771ecf675f0"),
    "details" : [ 
        {
            "title" : "Price",
            "content" : "",
            "is_private" : true,
            "order" : 1.0,
            "type" : "text"
        }
    ]
}
dsharew
  • 10,377
  • 6
  • 49
  • 75