2017-01-29 81 views
0
提取值

考虑一下:从JSON对象的数组MongoDB中

{ 
    "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" 
    } 
    ] 
} 

我试图拔出由乔治·卢卡斯执导的所有电影。这是我曾尝试和返回的所有项目:

db.movies.find({"movies.director" : "George Lucas"}).pretty() 

而且这导致一个错误:

db.movies.find({"$pull" : {"movies.director" : "George Lucas"}}).pretty() 

请让我知道如何查询数据库,检索只有电影,其中导演钥匙有“乔治卢卡斯”作为价值。

+0

使用[$过滤器(https://docs.mongodb.com/manual/reference/operator/aggregation/filter/) – Veeram

+0

你怎么能做到这一点? – JohnSnow

+0

您需要使用$ unwind聚合函数 – akinjide

回答

3

您需要使用聚合框架:

db.movies.aggregate([ 
{ 
    $unwind : "$movies" 
}, 
{ 
    $match : { 
     "movies.director" : "George Lucas" 
    } 
}, 
{ 
    $project : { 
     _id : 0, 
     movies : 1 
    } 
} 
]) 
+0

当我运行该函数时会引发错误。 – JohnSnow

+0

@JohnNoob:我在放松阶段错过了'$'。编辑答案。现在应该没问题。 – ares

+0

是的,现在工作..只需要读一下你现在做了什么 – JohnSnow