我是 mongodb 的新手,我正在嘗試創建一個包含帖子和標簽的資料庫,其中每個帖子都可以有許多標簽,就像這樣(簡化)
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]
}
]
如何獲取所有標簽的串列?(即回傳[1,2,3,4,5])
uj5u.com熱心網友回復:
您可以使用類似這樣的方法來獲取每個檔案的所有標簽:
db.collection.aggregate([
{
$project: {
_id: 0,
tags: {
$reduce: {
input: "$posts.post.tags",
initialValue: [],
in: {
"$setUnion": [
"$$value",
"$$this"
]
}
}
}
}
}
])
解釋:
投影陣列 posts.post.tag 并在所有檔案標簽陣列元素之間使用 $setUnion 應用 reduce 操作以接收不同的標簽串列
操場
像這樣為每個集合獲取不同的標簽:
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"
]
}
}
}
}
}
])
解釋: 1.project 每個檔案的所有標簽。2. 對集合中的所有標簽進行分組。3. setUnion 到集合中的所有標簽陣列。
游樂場2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/453623.html
標籤:mongodb
