let serviceData = await getServiceData();
我正在從外部服務中獲取一些資料,該服務是一個物件陣列,例如:
[
{
_id
x
y
},
...
]
有沒有辦法在查找階段使用這個結果,而無需實際將其創建為資料庫中的集合?我想為另一個具有類似架構的集合創建聚合
new Schema({
_id
a
b
);
并在其中進行查找:
{
from: serviceData,
localField: "_id",
foreignField: "_id",
as: "data"
}
最后得到
[
{
_id
x
y
a
b
},
...
]
uj5u.com熱心網友回復:
試試這個:
{
$set: {
data: {
$filter: {
input: serviceData,
cond: { $eq: ["$$this._id", "$_id"] }
}
}
}
}
uj5u.com熱心網友回復:
您已經serviceData在客戶端代碼中,所以您需要做的就是$match進入您的目標集合,然后像這樣在客戶端“加入”材料:
var svcdata = [
{ _id: 1, x: 3, y: 7 },
{ _id: 2, x: 8, y: 9 }
];
// Create an array of _id from the given serviceData:
var zzz = svcdata.map(x => x['_id']);
// Create a key lookup dictionary (_id => rest of serviceData).
// All fields will be picked up; no need to enumerate
// x, y, z, etc.:
var svcdict = {};
svcdata.forEach(function(item) {
svcdict[item['_id']] = item;
});
// This is all you need to find the material in your collection:
c=db.foo.aggregate([
{$match: {_id: {$in: zzz} }}
]);
// As you pull each doc from the DB, key-match on _id and add it
// to the materal:
c.forEach(function(doc) {
doc['svcdata'] = svcdict[doc['_id']];
printjson(doc);
});
它最終看起來像這樣:
{
"_id" : 1,
"name" : "N1",
"svcdata" : {
"_id" : 1,
"x" : 3,
"y" : 7
}
}
{
"_id" : 2,
"name" : "N2",
"svcdata" : {
"_id" : 2,
"x" : 8,
"y" : 9
}
}
這是一種“安全”的方法,因為您可以避免傳入serviceData欄位與檔案中的欄位的名稱沖突,即它是命名空間的。當然,您可以選擇一般地迭代svcdict[doc[_id]]并將每個欄位推送到來自 MongoDB 的“根”檔案中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377418.html
上一篇:不考慮空值的排序
