假設我在 1 個集合中有 4 個檔案
{
id: 1,
text: "Some text",
paragraph: 1
}
{
id: 2,
text: "This has field paragraph 2",
paragraph: 2
}
{
id: 3,
text: "This also has paragraph 2 field",
paragraph: 2
}
{
id: 4,
text: "Some other text",
paragraph: 3
}
過濾結果的期望輸出必須是
{
id: 1,
text: "Some text",
paragraph: 1
}
{
id: 2,
text: "This has field paragraph 2 This also has paragraph 2 field",
paragraph: 2
}
{
id: 3,
text: "Some other text",
paragraph: 3
}
如何過濾 mongodb 集合以獲得上述結果或以任何其他方式生成具有所需結果的集合并將其作為回應發送。
uj5u.com熱心網友回復:
$group- 按paragraph和分組$pushtext到陣列欄位 (texts)。$project- 裝飾輸出檔案。用于$reduce將$concattexts欄位陣列化為字串。并且不要忘記使用$trim來洗掉起始空格。$sort- 按id升序排序。
db.collection.aggregate([
{
$group: {
_id: "$paragraph",
texts: {
"$push": "$text"
}
}
},
{
$project: {
_id: 0,
id: "$_id",
paragraph: "$_id",
text: {
$trim: {
input: {
$reduce: {
"input": "$texts",
"initialValue": "",
"in": {
$concat: [
"$$value",
" ",
"$$this"
]
}
}
}
}
}
}
},
{
$sort: {
id: 1
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/351980.html
標籤:MongoDB
下一篇:Python中的高效求和
