-2

I have data like this

{
   "_id":1,
   "v_name":"Hair Patch in Delhi",
   "v_url":"https://www.testurlvideo.com",
   "v_comments":[
      {
         "user":"Kush Khurana",
         "comment":"Awesome Video"
      },
      {
         "user":"Nikhil",
         "comment":"Keep up the good videos"
      },
      {
         "user":"Kush Khurana",
         "comment":"Very good and Awesome Video"
      }
   ]
}

But I want the data like this below

{
   "_id":1,
   "v_comments":[
      {
         "user":"Nikhil",
         "comment":"Keep up the good videos"
      }
   ]
}

What query I need in MongoDB?

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • 1
    Does this answer your question? [How to filter array in subdocument with MongoDB](https://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb) – turivishal Nov 21 '20 at 16:02

2 Answers2

0

You only need $filter to select the subdocuments in array and $project to output only fields you want.

Check this:

db.collection.aggregate([
  {
    "$match": {
      "_id": 1
    }
  },
  {
    "$project": {
      "v_comments": {
        "$filter": {
          "input": "$v_comments",
          "as": "arr",
          "cond": {
            "$eq": [
              "$$arr.user",
              "Nikhil"
            ]
          }
        }
      }
    }
  }
])

First $match by _id (optional if you want look for only in one specific document).
And then $project to show the field v_comments filtered by those object whose user is Nikhil. Example here

J.F.
  • 13,927
  • 9
  • 27
  • 65
0

Warning: following methods only return one array element.


var query = { "_id": 1, "v_comments.user": "Nikhil" }
var project =   { "v_comments.$": 1 }

db.collection.find( query, project )

Explanation

  • Syntax: db.collection.find(query, projection)
  • It projects only the array element that matches the query.

Another simple one:

db.collection.find(
    { "_id": 1 },
    { "v_comments": { "$elemMatch": { "user": "Nikhil" } } }
)

Playground

Minsky
  • 2,277
  • 10
  • 19
  • 1
    For information, The `$` and `$elemMatch` will return only single matched element form array field, as per OP's question, single user can have multiple comments! – turivishal Nov 21 '20 at 16:35