我有 3 個收藏
用戶
{
"_id": "P4SpYVd1KjBaF4SKyVw0E",
"login": "User-01",
"name": "John",
"lastName": "Doe",
}
Moods
是時間序列集合
{
"source": {
"userId": "P4SpYVd1KjBaF4SKyVw0E",
},
"timestamp": "2022-06-11T12:44:13.333Z",
"mood": "bad",
"_id": "62a352b83859aaf975c6332d",
}
contactRequest
也是時間序列集合
{
"timestamp": "2022-06-11T15:25:13.333Z",
"source" : {
"userId":"P4SpYVd1KjBaF4SKyVw0E"
},
"resolve": false,
"_id": "62a351ff3859aaf975c63329"
}
我想實作看起來像這樣的最終檔案:
Final
{
"_id": "P4SpYVd1KjBaF4SKyVw0E",
"login": "User-01",
"name": "John",
"lastName": "Doe",
"calendar": [
{
"timestamp": "2022-06-11T12:44:13.333Z" //which is moods.timestamp,
"mood": {
"source": {
"userId": "P4SpYVd1KjBaF4SKyVw0E",
},
"timestamp": "2022-06-11T12:44:13.333Z",
"mood": "bad",
"_id": "62a352b83859aaf975c6332d",
},
"contactRequest": [
{
"timestamp": "2022-06-11T15:25:13.333Z", //contactRequest is grouping by date with moods
"source" : {
"userId":"P4SpYVd1KjBaF4SKyVw0E"
},
"resolve": true,
"_id": "62a351ff3859aaf975c63329"
},
{
"timestamp": "2022-06-11T18:23:13.333Z",
"source" : {
"userId":"P4SpYVd1KjBaF4SKyVw0E"
},
"resolve": false,
"_id": "62a351ff3859aaf975c63329"
},
]
}
}
]
}
我嘗試使用$lookup引數對其進行聚合,它在用戶檔案中給了我兩個單獨的欄位,這令人不滿意。
我也使用了 $project引數,但問題在于按日期分組結果。
是否有可能實作這一點,在最終自己的形狀檔案中聚合乘法集合?過去有人試圖這樣做嗎?
這是一個mongoplayground.net嘗試,它不能正確回傳所有內容。
uj5u.com熱心網友回復:
使用問題的 mongoplayground 作為起點,我對其進行了一些修改以按要求回傳檔案。
db.users.aggregate([
{
"$match": {
// id comes from param
"_id": "P4SpYVd1KjBaF4SKyVw0E"
}
},
{
"$lookup": {
"from": "moods",
"localField": "_id",
"foreignField": "source.userId",
"pipeline": [
{
"$lookup": {
"from": "contactRequests",
"localField": "source.userId",
"foreignField": "source.userId",
"let": {
// truncate timestamp to start of day
"moodsDate": { "$dateTrunc": { "date": "$timestamp", "unit": "day" } }
},
"pipeline": [
{
"$match": {
"$expr": {
"$eq": [
"$$moodsDate",
{ // truncate timestamp to start of day
"$dateTrunc": { "date": "$timestamp", "unit": "day" }
}
]
}
}
}
],
"as": "contactRequests"
}
},
{
// don't return mood doc if no requests
"$match": {
"$expr": { "$gt": [ { "$size": "$contactRequests" }, 0 ] }
}
}
],
as: "calendar"
}
}
])
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/492052.html
標籤:javascript 节点.js 数据库 mongodb 猫鼬
