I have a "class" document as:
{
className: "AAA",
students: [
{name:"An", age:"13"},
{name:"Hao", age:"13"},
{name:"John", age:"14"},
{name:"Hung", age:"12"}
]
}
我希望能够获取名字为“An”的学生,只在数组“students”中匹配元素。我可以使用find()函数来完成:
>db.class.find({"students.name":"An"}, {"students.$":true})
{
"_id" : ObjectId("548b01815a06570735b946c1"),
"students" : [
{
"name" : "An",
"age" : "13"
}
]}
这个没问题,但是当我按照以下聚合的方式操作时,出现了错误:
db.class.aggregate([
{$match:{"students.name":'An'}},
{$project:{"students.$":true}}
])
错误信息如下:
uncaught exception: aggregate failed: {
"errmsg" : "exception: FieldPath field names may not start with '$'.",
"code" : 16410,
"ok" : 0
}
为什么我不能在aggregate()的$project操作符中使用"$"来表示数组,而在find()的project操作符中可以使用?