如果查询找到角色“elite”
,我想检索帐户数组我尝试
db.users.aggregate(
{ $match : { "account.role" : "Elite" } }
);
但我有所反对......
{
"_id" : ObjectId("7623902143981943"),
"account" : [
{
"role" : "Elite",
"action" : [
"create",
"read",
"update",
"delete"
],
"extra" : {
account:[1,2,3,4]
}
},
{
"role" : "User",
"action" : [
"create",
"read",
"update",
"delete"
],
"extra" : {
account:[10]
}
}
],
}
如果是查询的肯定结果,我可以只检索额外的数组(帐号:[1,2,3,4])吗?或者我必须解析收到的对象? (架构非常简化,但我有很多角色)
答案 0 :(得分:1)
//Order of $unwind and $match matters
db.users.aggregate(
{$unwind: "$account"},
{$match : { "account.role" : "Elite" }},
{$project : { "extra.account" : 1}}
);
<强>解释强>
$ unwind将数组拆分为不同的元素。看到
的效果 db.users.aggregate({$unwind: "$account"})
然后你将元素与{“account.role”:“Elite”}匹配。见效果:
db.users.aggregate(
{$unwind: "$account"},
{$match : { "account.role" : "Elite" }}
);
然后你最终投射出所需的字段
db.users.aggregate(
{$unwind: "$account"},
{$match : { "account.role" : "Elite" }},
{$project : { "extra.account" : 1}}
);
//You can also remove the _id filed (included by default with:
db.users.aggregate(
{$unwind: "$account"},
{$match : { "account.role" : "Elite" }},
{$project : { _id: 0, "extra.account" : 1}}
);
OLD ANSWER
您必须使用投影: db.users.aggregate( {$ match:{“account.role”:“Elite”}}, {$ project:{“extra.account”:1}} );
此外,如果您只是匹配文档,则无需使用聚合framewrok,您只需使用:
// No projection here
db.users.find({"account.role" : "Elite"})
或
// Only returns the _id field + "extra.account" field if exists. By default the _id field is included
db.users.find({"account.role" : "Elite"}, { "extra.account" : 1})
// Only returns the "extra.account" field if exists
db.users.find({"account.role" : "Elite"}, { _id: 0, "extra.account" : 1})