我正在使用带有NodeJ的MongoDB,我正在尝试提取部分文档,以便在我的应用程序中使用它。我想直接在mongo中做这一切,但我不确定它是否可能。我有一堆文件结构:
{ _id:something1,
firstName: somefirstname,
gyms: [{ name: "somename1",
address: "somewhere1"},
{ name: "somename2",
address: "somewhere2"}]
},
{ _id:something2,
firstName: somefirstname,
gyms: [{ name: "somename3",
address: "somewhere3"},
{ name: "somename4",
address: "somewhere4"}]
},
{ _id:something3,
firstName: somefirstname,
gyms: [{ name: "somename5",
address: "somewhere5"},
{ name: "somename6",
address: "somewhere6"}]
}
是否有可能以某种方式提取数据,所以我最终会得到如下所示的结构?
[{ id: soemthing1,
name: "somename1",
address: "somewhere1"},
{ id: soemthing1,
name: "somename2",
address: "somewhere2"},
{ id: soemthing2,
name: "somename3",
address: "somewhere3"},
{ id: soemthing2,
name: "somename4",
address: "somewhere4"},
{ id: soemthing3,
name: "somename5",
address: "somewhere5"},
{ id: soemthing3,
name: "somename6",
address: "somewhere6"}]
答案 0 :(得分:2)
在MongoDB聚合框架中有运算符$unwind
db.test.aggregate([
{$unwind : "$gyms"},
{$project: {
_id: 0,
id : '$_id' ,
firstName: 1,
name: '$gyms.name',
address: '$gyms.address'
}}
])