skip to Main Content

My sample record:

[   
    {
        "name": "name1",
        "status": "one",
        "unit": [
        ],
        "child": [],
        "element": [
            "6604"
        ],
        "tags": [
            "tag1",
            "tag2",
            "tag3"
        ]
    },
    {
        "name": "name2",
        "status": "one",
        "unit": [
        ],
        "child": [],
        "element": [
            "6604"
        ],
        "tags": [
            "tag1",
            "tag2",
            "tag3",
            "tag4"
        ]
    }
]

I tried in this way to get
tagsdata = dbname.distinct(‘tags.values’)

expecting the output: "tag1","tag2","tag3","tag4"

All unique values form the key field.

2

Answers


  1. add
    unique:true
    In mongoDb model and while inserting data do check if data doesnt exists with same name with : DB.findOne

    Login or Signup to reply.
  2. MongoDB is a document database. It will never return a bare string or a list of strings.

    Using aggregation you might

    • $unwind the tags array
    • $group using $addToSet to keep the unique tags
    • $project to sort the returned array

    That pipeline might look like:

    [
      {$unwind: "$tags"},
      {$group: {
          _id: null,
          tags: {$addToSet: "$tags"}
      }},
      {$project: {
        _id: 0,
        tags: {$sortArray: {
            input: "$tags",
            sortBy: 1
        }}
      }}
    ]
    

    Which returns:

    [{"tags": [ "tag1", "tag2", "tag3", "tag4"]}]
    

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search