1

Need to count distinct tags on all registers in a mongodb query, using JS.

Register structure:

  {
  "_id": {
    "$oid": "62e593aed8fd9808777225e8"
  },
  "title": "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”",
  "author": {
    "name": "Albert Einstein",
    "url": "https://quotes.toscrape.com/author/Albert-Einstein"
  },
  "tag": [
    "change",
    "deep-thoughts",
    "thinking",
    "world"
  ]
  }

1 Answer 1

1

This could be useful. In addition to get the different values for the field, it returns the number of appearances:

db.collection.aggregate([
  {
    "$unwind": "$tag"
  },
  {
    "$group": {
      "_id": "$tag",
      "total": {
        "$sum": 1
      }
    }
  },
  
])

You can try here: https://mongoplayground.net/p/yXLYkJKO3Wf

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.