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])
CodePudding user response:
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
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.