考虑一下:
{
"movies": [
{
"title": "Star Wars",
"year": 1977,
"director": "George Lucas"
},
{
"title": "The Empire Strikes Back",
"year": 1980,
"director": "Irvin Kershner"
},
{
"title": "Return of the Jedi",
"year": 1983,
"director": "Richard Marquand"
},
{
"title": "The Phantom Menace",
"year": 1999,
"director": "George Lucas"
},
{
"title": "Attack of the Clones",
"year": 2002,
"director": "George Lucas"
},
{
"title": "Revenge of the Sith",
"year": 2005,
"director": "George Lucas"
},
{
"title": "The Force Awakens",
"year": 2015,
"director": "J.J. Abrams"
}
]
}
我正试图推出Geroge Lucas导演的所有电影。这是我尝试过的,它会返回所有项目:
db.movies.find( {"movies.director" : "George Lucas"} ).pretty()
这也会导致错误:
db.movies.find({"$pull" : {"movies.director" : "George Lucas"}}).pretty()
请让我知道如何查询数据库以仅检索导演键具有“George Lucas”值的电影。
答案 0 :(得分:3)
您需要使用聚合框架:
db.movies.aggregate([
{
$unwind : "$movies"
},
{
$match : {
"movies.director" : "George Lucas"
}
},
{
$project : {
_id : 0,
movies : 1
}
}
])