我正在使用 findOne 查詢資料庫,它只回傳一個檔案。現在,我想要一個物件中該檔案的一些欄位和另一個物件中的其他欄位,這兩個欄位都包裝在一個物件中。例如,我有一個名為 Bus 的表,其中包含以下欄位 -
_id,
busNo,
city,
agency,
date,
ticketPrice,
helper,
driver,
totalCollection
我的查找一個查詢回傳一個檔案,但我希望它采用以下格式 -
existingAggr - {
"result": [
{
"_id": "630dcd0c652489bca1b319f7",
"busNo": "123",
"city": "32",
"agency": "58",
"date": "2022-08-29T00:00:00.000Z",
}
],
"aggregates": {
"ticketPrice": 8,
"totalCollection": 402,
"helper": 0,
"driver": 23,
}
}
我希望通過單一訪問資料庫,或者我們可以做一些 javascript 計算以進一步以這種方式帶來我的結果,但我似乎無法達到解決方案。目前,我正在使用以下代碼 -
const res = await Bus.findOne(
{ busNo, date },
{
_id :1,
busNo:1,
city:1,
agency:1,
date:1,
ticketPrice:1,
helper:1,
driver:1,
totalCollection:1
}
);
這將回傳所有欄位。
uj5u.com熱心網友回復:
給定結果,您可以直接從結果中創建新物件。
const res = await BusDayWise.findOne(
{ ...filter },
{ session: mongoSession }
);
const result = [
{
"_id": res._id,
"busNo": res.busNo,
"city": res.city,
"agency": res/agency,
"date": res.date,
}
],
const aggregates =
{
"ticketPrice": res.ticketPrice,
"totalCollection": res.totalCollection,
"helper": res.helper,
"driver": res.driver,
}
更高級的答案
您可以擁有一個僅從字典中檢索特定鍵的功能
function subDict(dict, keys){
const newDict = {};
keys.forEach(key => newDict[key] = dict[key]);
return newDict
}
test = {"a": 1, "b": 2, "c": 3}
keys = ["a", "c"];
newTest = subDict(test, keys); // {"a": 1; "c": 3}
所以在你的情況下
const result = subDict(res, ["_id", "busNo", "city","agency", "date"]);
const aggregates = subDict(res, ["ticketPrice", "totalCollection", "helper", "driver"]);
uj5u.com熱心網友回復:
這對于投影應該是非常簡單的,投影是轉換檔案形狀的行為。
您編輯的問題現在包括對最簡單型別投影的參考,但還有更多。在你的情況下,看起來你仍然可以使用一個相對簡單的,試試這個:
{
"result._id": "$_id",
"result.busNo": "$busNo",
"result.city": "$city",
"result.agency": "$agency",
"result.date": "$date",
"aggregates.ticketPrice": "$ticketPrice",
"aggregates.totalCollection": "$totalCollection",
"aggregates.helper": "$helper",
"aggregates.driver": "$driver",
_id: 0
}
操場示范在這里。
如果您要在每次檢索資料時都這樣做,那么您可能希望更改檔案的架構,因為它們存盤在資料庫中。或者,您可以創建一個定義此投影的視圖,然后在您每次查詢資料時自動應用該投影,而不必依賴客戶端來請求它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518133.html
上一篇:在pom.xml檔案中沒有硬編碼db配置的query-dsl-sql配置?
下一篇:未找到檔案時$count不回傳0
