我有以下檔案
{"_id": "1", "posts": [{"text": "all day long I dream about", "datetime": "123"}, {"text": "all day long ", "datetime": "321"}]}
{"_id": "1", "posts": [{"text": "all day long I dream about", "datetime": "123"}, {"text": "all day long ", "datetime": "8888"}, {"text": "I became very hungry after watching this movie...", "datetime": "8885"}]}
我希望將文本欄位連接到一個新欄位中,將日期時間欄位連接到一個新欄位中,同時還將陣列元素連接到一個字串中,新欄位如下所示
{"_id": "1", "text": "all day long I dream about, all day long ", "datetime": "123, 321"}
{"_id": "1", "text": "all day long I dream about, all day long ,I became very hungry after watching this movie... ", "datetime": "123, 8888, 8885"}
直接在 Mongodb 服務器上執行此操作的最佳方法是什么?有沒有這樣的方法?
uj5u.com熱心網友回復:
詢問
- 減少以
null(相同代碼2x)開頭的帖子 - 如果不為空
(concat all_string ", " current_string) - 否則
current_string(這只發生在第一個字串上)
*檢查是否不是null僅針對第一個字串,沒有類似 ", string1, string2 ...." 我們這樣做是為了避免添加,到第一個字串
*您也可以使用 1 reduce 來執行此操作,但代碼會更復雜
測驗代碼在這里
aggregate(
[{"$set":
{"text":
{"$reduce":
{"input":"$posts",
"initialValue":null,
"in":
{"$cond":
["$$value", {"$concat":["$$value", ", ", "$$this.text"]},
"$$this.text"]}}}}},
{"$set":
{"datetime":
{"$reduce":
{"input":"$posts",
"initialValue":null,
"in":
{"$cond":
["$$value", {"$concat":["$$value", ", ", "$$this.datetime"]},
"$$this.datetime"]}}}}}
{"$unset":["posts"]}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406705.html
標籤:
上一篇:如何使用MongoDB的$graphLookup獲取所有子檔案
下一篇:突出顯示重復項并要求洗掉重復項
