1

Suppose I have following documents in my collection

{  
   "_id":ObjectId("562e7c594c12942f08fe4192"),
   "tags" : [ 
        {
            "tagName" : "fun",
            "created" : ISODate("2016-01-22T06:13:56.510Z")
        }, 
        {
            "tagName" : "cool",
            "created" : ISODate("2016-01-22T06:13:56.509Z")
        }, 
        {
            "tagName" : "good",
            "created" : ISODate("2016-01-22T06:13:56.509Z")
        }
    ]
},
{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "tags" : [ 
        {
            "tagName" : "super",
            "created" : ISODate("2016-01-22T06:13:56.509Z")
        }, 
        {
            "tagName" : "fun",
            "created" : ISODate("2016-01-22T06:13:56.509Z")
        }
    ]
}

I want to search relative tags and want to display tag array only.

How can I query to get the list of tag names?

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
Harsha Vardhan
  • 411
  • 1
  • 7
  • 16
  • Not sure what you mean here. Do you just want the "tags" array to display only the content of "tagName"? Or do you just want a "distinct" list of all values in "tagName" for the collection? – Blakes Seven Jan 29 '16 at 06:08
  • @BlakesSeven I just want tagName as array, which matches to my search string. – Harsha Vardhan Jan 29 '16 at 06:13
  • Still really unclear what you are expecting. Why is this not your answer: http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection ? If you expect something different then please at least supply your sample query data and expected response. – Blakes Seven Jan 29 '16 at 06:16
  • Do you need output like [ { "tagName" : "fun" }, {"tagName" : "cool" }] this? – Ashutosh Jan 29 '16 at 07:29

1 Answers1

1

To only query a specific field in MongoDB you can use the find method with the projection parameter: https://docs.mongodb.org/manual/reference/method/db.collection.find/

db.test.find({}, {"tags.tagName":1,"_id":0}).pretty()
{
    "tags" : [
        {
            "tagName" : "fun"
        },
        {
            "tagName" : "cool"
        },
        {
            "tagName" : "good"
        }
    ]
}

The first parameter is blank {} because you don't have any query and the second parameter is your projection. With an embedded document you have to use the dot notation "tags.tagName". The "_id":0 to not display the _id field.

Mehdi
  • 11
  • 1