我试图在mongodb中查看子节点数据
我用mongodb编写的查询是 -
db.users.aggregate({$unwind: '$social'} ,
{ $project : { name: '$name' ,fb: '$social.facebook' } } );
我只想查看名称和facebook字段
但它将数据显示为 -
/* 1 */
{
"_id" : ObjectId("583d94b42a7b4dfc334d1ab7"),
"name" : "Person Name",
"fb" : "www.fb.com/maria.mongodb"
}
/* 2 */
{
"_id" : ObjectId("583d94b42a7b4dfc334d1ab7"),
"name" : "Person Name"
}
/* 3 */
{
"_id" : ObjectId("583da2a52a7b4dfc334d1ab8"),
"name" : "Some Name",
"fb" : "www.fb.com/some.name"
}
/* 4 */
{
"_id" : ObjectId("583da2a52a7b4dfc334d1ab8"),
"name" : "Some Name"
}
如您所见,2和4数据中的数据没有fb字段。
我所拥有的原始数据是 -
/* 1 */
{
"_id" : ObjectId("583d94b42a7b4dfc334d1ab7"),
"name" : "Person Name",
"social" : [
{
"facebook" : "www.fb.com/maria.mongodb",
"privacy" : true
},
{
"twitter" : "www.tw.com/mongodb",
"privacy" : false
}
],
"personal" : [
{
"cell_no" : "+1-99082198414",
"privacy" : true
},
{
"email" : "maria@mongodb.com",
"privacy" : false
}
]
}
/* 2 */
{
"_id" : ObjectId("583da2a52a7b4dfc334d1ab8"),
"name" : "Some Name",
"social" : [
{
"facebook" : "www.fb.com/some.name",
"privacy" : true
},
{
"twitter" : "www.tw.com/mongodb",
"privacy" : false
}
]
}
答案 0 :(得分:1)
试试这个,你需要在投射前只匹配social.facebook所在的文档。
db.users.aggregate([
{ $unwind: '$social' },
{ $match: { 'social.facebook': { $exists: true } } },
{ $project : { _id: 0, name: '$name', fb: '$social.facebook' } }
]);
结果如下:
{ "name" : "Person Name", "fb" : "www.fb.com/maria.mongodb" }
{ "name" : "Some Name", "fb" : "www.fb.com/some.name" }