【问题标题】:Golang nested objects in MongoDBMongoDB中的Golang嵌套对象
【发布时间】:2015-02-05 02:02:28
【问题描述】:

我目前正在开发一个允许用户对某些对象进行评分的小型应用程序,我的数据库 (MongoDB) 结构如下所示

Movie {
    Id int
    Name string
}
Actor {
    Id int
    Name string
    Age int
}
Movie_Actors {
    Movie Movie
    Actor Actor
}
User {
    Id int
    Username string
    Password string
}
Rating {
    Id int
    User User
    Actor Actor
    Rating int
}

当我想在Movie 中选择所有ActorsRatings 少于5 时,我的问题就开始了

// db *mgo.Database
c := db.C('ratings')
err := c.Find(...)

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    对于这个问题,我会对你的模式进行一些非规范化,以使在 MongoDB 中的查询更加自然。仅查看此查询所需的类型,您可能会使用以下内容:

    type Movie struct {
        Id     bson.ObjectId `_id,omitempty`
        Name   string
        Actors []bson.ObjectId
    }
    
    type Actor struct {
        Id     bson.ObjectId `_id,omitempty`
        Name     string
        Age      int
        Ratings []Rating
        NRatings int
    }
    

    这里,电影直接嵌入了演员 ID,演员在与评分本身不同的字段中跟踪评分数量。如果您只想运行这种单一类型的查询,您可以通过将电影直接嵌入到其中播放的 Actor 中来完全非规范化数据模型。这将进一步简化查询,但也会产生大量重复信息,并阻止您将电影作为单独的实体处理。

    请参阅the documentation on schema design,了解有关这些权衡的讨论。

    在此设计中,您可以使用以下方法找到评分低于 5 的电影Fantastic Mr. Fox 中的演员:

    // Find the actors in the movie
    var m Movie
    db.C("movies").Find(bson.M{"name": "Fantastic Mr. Fox"}).One(&m)
    
    // Filter the actors to find those with less than 5 ratings.
    var results []Actor
    db.C("actors").Find(bson.M{"_id": bson.M{"$in": m.Actors}, "nratings": bson.M{"$lt": 5}}).All(&results)
    fmt.Println(results)
    

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多