我有一份文件,Model
是这样的:
{
name: String,
user: String,
components: [{
alias: String,
name: String,
...etc...
}]
}
我想制定一个响应,它只返回给定文档的component.alias
数组。
例如,如果我有:
{
name: "doc1",
components: [{alias: "alias1", ...}, {alias: "alias2", ...}]
}
我想结束["alias1", "alias2"]
到目前为止,我有:
Model.findById(
modelId,
{ "components.alias": 1, _id: 0 },
(err, docs) => {
console.log(docs)
}
);
但是这给了我:
{
"components": [
{
"alias": "alias1"
}
]
}
有什么想法吗?
答案 0 :(得分:0)
使用聚合,MongoDB查询。
db.getCollection('Model').aggregate([
{ "$unwind": "$components" },
{ "$group": { "_id": "$components.alias" }}
]).map(function(el) { return el._id })
Node.js代码
Model.aggregate([
{ "$match": { "name": "doc1" } }, // any condition
{ "$unwind": "$components" },
{ "$group": { "_id": "$name", components: { $push: "$components.alias" } } }
]).then((data)=>console.log(data))
输出:
{
"_id": "doc1",
"emails": [
"alias1",
"alias2"
]
}