Search code examples
c#arraysmongodbsubdocumentmongodb.driver

Mongodb + C#: how to query sub-document and order by its used most


I have the collection Sites like this

 {
   _id: ObjectId("5ed4d2ed8a98dd17c467c040"),
   name:"Name1",
   description:"Desc1",
   tags:[
      "Tag1",
      "Tag3"
   ]
 },
 {
   _id: ObjectId("5ed4d2ed8a98dd17c467c040"),
   name:"Name2",
   description:"Desc2",
   tags:[
      "Tag1",
      "Tag3"
   ]
 },
 {
   _id: ObjectId("5ed4d2ed8a98dd17c467c040"),
   name:"Name3",
   description:"Desc3",
   tags:[
      "Tag1",
      "Tag4"
   ]
 },
 {
   _id: ObjectId("5ed4d2ed8a98dd17c467c040"),
   name:"Name4",
   description:"Desc4",
   tags:[
      "Tag3",
      "Tag4"
   ]
 },
 {
   _id: ObjectId("5ed4d2ed8a98dd17c467c040"),
   name:"Name5",
   description:"Desc6",
   tags:[
      "Tag1",
      "Tag2"
   ]
 }
]

I want to query all tags with an order by a tag that is used most.

So with the example, the query should be return

"Tag1", "Tag3", "Tag4", "Tag2"

Because

Tag1 appears most 4 times

Tag3 appears 3 times

Tag4 appears 2 times

And final Tag2

Please help me to make the query like that.

Thanks in advance.


Solution

  • If you want just the tags sorted by count,you can try this.

    db.collection.aggregate([
      {
        "$unwind": "$tags"
      },
      {
        "$group": {
          "_id": "$tags",
          "count": {
            "$sum": 1
          }
        }
      },
      {
        "$sort": {
          "count": -1
        }
      },
      {
        "$group": {
          "_id": null,
          "tags": {
            "$push": "$_id"
          }
        }
      },
      {
        "$unset": "_id"
      }
    ])
    

    This makes it an array of sorted tags.The important part is until the $sort.

    You can try the code here also