0

I'm new to mongodb, and I'm trying to make a database that has posts and tags, where each post can have numerous tags, something like this (simplified)

posts: [
 post:{
   id: dkdkd,
   title: hello,
   body: hello world,
   tags: [1,2,3]
 },
 post:{
   id: ccc,
   title: hello2,
   body: hello world2,
   tags: [3,4,5]
 }
]

how can I get a list of all the tags? (i.e. returns [1,2,3,4,5])

1 Answer 1

1

You may use something like this to get all tags per document:

db.collection.aggregate([
{
  $project: {
    _id: 0,
    tags: {
      $reduce: {
        input: "$posts.post.tags",
        initialValue: [],
        in: {
          "$setUnion": [
            "$$value",
            "$$this"
          ]
        }
      }
    }
  }
}
])

Explained:

Project the array posts.post.tag and apply reduce operation with $setUnion between all documents tag array elements to receive distinct list of tags

playground

And something like this to take distinct tags per collection:

db.collection.aggregate([
{
$project: {
  _id: 0,
  tags: {
    $reduce: {
      input: "$posts.post.tags",
      initialValue: [],
      in: {
        "$setUnion": [
          "$$value",
          "$$this"
          ]
        }
      }
    }
  }
},
{
  $group: {
  _id: "Total",
  tags: {
    "$push": "$tags"
    }
  }
},
{
$project: {
  _id: 0,
  tags: {
    $reduce: {
      input: "$tags",
      initialValue: [],
      in: {
        "$setUnion": [
          "$$value",
          "$$this"
          ]
        }
      }
    }
  }
}
])

Explained: 1.project all tags per document. 2. Group all tags from collection. 3. setUnion to all tags arrays in collection.

playground2

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

2 Comments

Thanx! But I don't understand the diff between the 2 answers, the first is also distinct..
1st is per document , 2nd per collection

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.