Javascript 有没有办法从mongodb中检索数据作为键值映射,其中键是字段的值(使用Mongoose)
我的Mongodb收藏中有以下数据:Javascript 有没有办法从mongodb中检索数据作为键值映射,其中键是字段的值(使用Mongoose),javascript,mongodb,performance,mongoose,aggregate,Javascript,Mongodb,Performance,Mongoose,Aggregate,我的Mongodb收藏中有以下数据: {_id: xxx1, fieldA: valueA_1, fieldB: valueB_1, fieldC: valueC_1}, {_id: xxx2, fieldA: valueA_1, fieldB: valueB_2, fieldC: valueC_2}, {_id: xxx3, fieldA: valueA_2, fieldB: valueB_3, fieldC: valueC_3}, 是否有Mongodb聚合运算符或类似运算符返回此类结构:
{_id: xxx1, fieldA: valueA_1, fieldB: valueB_1, fieldC: valueC_1},
{_id: xxx2, fieldA: valueA_1, fieldB: valueB_2, fieldC: valueC_2},
{_id: xxx3, fieldA: valueA_2, fieldB: valueB_3, fieldC: valueC_3},
是否有Mongodb聚合运算符或类似运算符返回此类结构:
{
"valueA_1": [
{_id: xxx1, fieldA: valueA_1, fieldB: valueB_1, fieldC: valueC_1},
{_id: xxx2, fieldA: valueA_1, fieldB: valueB_2, fieldC: valueC_2}
],
"valueA_2": [
{_id: xxx3, fieldA: valueA_2, fieldB: valueB_3, fieldC: valueC_3}
]
}
现在我正在做一个简单的Schema.find,然后对结果应用reduce函数:
data.reduce(function (map, obj) {
map[obj.fieldA] = map[obj.fieldA] ? [...map[obj.fieldA], obj] : [obj];
return map;
}, {});
我想知道如何仅使用mongodb\mongoose操作符完成此行为
还有,如果使用它们而不是reduce函数,性能是否会更好
谢谢大家! 试试这个
db.collection.aggregate([
{
$group: { // first group by the required fieldA
_id: "$fieldA",
docs: {
$push: "$$ROOT"
}
}
},
{
$group: { // this group to gather all documents in one array 'allDocsInOneArray' of objects
// each object has a key = the value of fieldA, and a value = an array of the docs belong to this fieldA
_id: null,
allDocsInOneArray: {
$push: {
k: "$_id", // the key of the object (should be the value of fieldA, which is the _id now after the first group stage)
v: "$docs" // an array of docs belong to this fieldA
// the object should be in this format { k: '', v: [] } in order to be able to convert the whole array to another object in $arrayToObject operation
}
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": "$allDocsInOneArray" // convert the array of objects to object with key = k (fieldA), value = v (its docs)
}
}
}
])
你可以
希望能有所帮助嗨,穆罕默德!看起来很完美。你能给我讲讲表演吗?哪种策略应该更好?我认为,如果您可以直接从db获得所需形状的数据,这将比使用JavaScript更好