【问题标题】:How do I query a nested object in MongoDB?如何查询 MongoDB 中的嵌套对象?
【发布时间】:2016-01-15 22:28:59
【问题描述】:

我有一个如下所示的 JSON 架构:

{
    "_id" : ObjectId("5692a3e124de1e0ce2dfda22"),
    "title" : "A Decade of Decadence, Pt. 2: Legacy of Dreams",
    "year" : 2013,
    "rated" : "PG-13",
    "released" : ISODate("2013-09-13T04:00:00Z"),
    "runtime" : 65,
    "countries" : [
            "USA"
    ],
    "genres" : [
            "Documentary"
    ],
    "director" : "Drew Glick",
    "writers" : [
            "Drew Glick"
    ],
    "actors" : [
            "Gordon Auld",
            "Howie Boulware Jr.",
            "Tod Boulware",
            "Chen Drachman"
    ],
    "plot" : "A behind the scenes look at the making of A Tiger in the Dark: The Decadence Saga.",
    "poster" : null,
    "imdb" : {
            "id" : "tt2199902",
            "rating" : 8,
            "votes" : 50
    },
    "awards" : {
            "wins" : 0,
            "nominations" : 0,
            "text" : ""
    },
    "type" : "movie"
}

我正在寻找一部 2013 年上映的电影,评级为 PG-13,并且没有获奖。我在 Mongo Shell 中尝试了以下查询,但没有运气:

db.movieDetails.find({rated: "PG-13", year:2013, awards: { wins : 0}})

有什么想法吗?

【问题讨论】:

    标签: json mongodb mongodb-query


    【解决方案1】:

    来自文档:

    当字段包含嵌入文档时,查询可以指定嵌入文档的完全匹配,也可以使用 dot notation 指定嵌入文档中各个字段的匹配

    db.movieDetails.find( { "rated": "PG-13", "year": 2013, "awards.wins" : 0 } )
    

    【讨论】:

      【解决方案2】:

      如果此 PG-13 评级查询对您有用:

      db.movieDetails.find({"rated": "PG-13"})

      然后我会尝试这样的事情:

      db.movieDetails.find({$and: [{"rated": "PG-13"}, {"year": 2013}, {"awards": { "wins" : 0}}]} )

      【讨论】:

      • 这个没有奖有用吗? db.movieDetails.find({$and: [{"rated": "PG-13"}, {"year": 2013}]} )
      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 2017-11-16
      • 2018-09-10
      相关资源
      最近更新 更多