假設我有一個學生對象數組字段,例如[{id:foo, name: bar, imageurl:baz}]
在課程集合中。並且我想僅返回在學生字段中具有給定學生ID的課程。
如果我使用$elemMatch
,我會在課程集合以及我想要的課程中獲得一堆文檔。有沒有辦法解決這個問題,或者我絕對必須做一些後期查詢過濾來只返回一個文檔?
編輯: 例如課程集合:
{
_id: 1,
course: "OOP 101",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 2,
course: "Programming 101",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 3,
course: "Database 101",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
預計如果我使用$elemMatch
找到課程傑夫正在輸出:
{
_id: 3,
course: "Database 101",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
與
{
_id: 1,
course: "OOP 101"
{
_id: 2,
course: "Programming 101"
}
{
_id: 3,
course: "Database 101",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
你能否:
如果你只想要其中的一個,你可能會與
$limit
階段一起使用聚合框架(在大多數情況下,你應該使用$sort
階段$limit
前)向我們展示一些樣本文件和預期產出? – chridam@chridam請參閱編輯? – wemadeit
我編輯了您的問題,根據您提供的一個鏈接顯示樣本集合。你能**顯示預期輸出的例子**嗎? –