Golang在MongoDB中嵌套对象 [英] Golang nested objects in MongoDB
问题描述
我目前正在研究一个允许用户对某些对象进行评分的小应用程序,我的数据库(MongoDB)结构如下所示:
电影{
Id int
名称字符串
}
演员{
Id int
名称字符串
年龄类型
}
Movie_Actors {
电影电影
演员Actor
}
用户{
Id int
用户名字符串
密码字符串
Rating {
Id int
User User
Actor Actor
Rating int
}
当我想要选择中的所有
小于5 Actors
Movie 等级
// db * mgo.Database
$对于这个问题,我会将你的模式非规范化,以便在MongoDB中查询更自然。只需查看此查询所需的类型,就可以使用以下内容:
c:= db.C('ratings')
err:= c.Find(...)
type Movie struct {
Id bson.ObjectId`_id,omitempty`
名称字符串
Actors [] bson.ObjectId
}
类型Actor结构{
Id bson.ObjectId` _id,omitempty`
名称字符串
年龄int
评级[]评级
NRatings int
}
这里,电影直接嵌入了演员ID,演员跟踪评分本身的分开字段中的评分数量。如果您只想运行这种单一类型的查询,则可以通过将电影直接嵌入播放其中的Actor中完全将数据模型非规范化。这将更加简化查询,但也会产生大量信息重复,并阻止您将电影作为单独的实体进行处理。 关于模式设计的文档讨论这些折衷。
在此设计中,您可以在电影中找到演员神奇先生福克斯使用以下方式评分少于5:
//找到电影中的演员
var电影
db.C(电影)。查找(bson.M {name:Fantastic Mr. Fox})。一个(& m)
//筛选演员以查找评分少于5的人。
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)
I'm currently working on a small application that allows users to rate certain objects, my database (MongoDB) structure looks like this
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 }
My problem begins when I want to select all
Actors
in aMovie
where there are less than 5Ratings
// db *mgo.Database c := db.C('ratings') err := c.Find(...)
解决方案For this problem, I would denormalize your schema a little to make querying in MongoDB more natural. Looking only at the types you need for this query, you might use the following:
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 }
Here the Movie directly embeds the Actor IDs, and the Actor keeps track of the number of ratings in a separate field from the ratings themselves. If you only wanted to run this single type of query, you could fully denormalize the data model by embedding the Movies directly into the Actors who played in them. This would simplify the query even more, but would also create a lot of duplication of information and prevent you from dealing with Movies as separate entities.
See the documentation on schema design for a discussion on these tradeoffs.
In this design, you can find the actors in the movie Fantastic Mr. Fox with fewer than 5 ratings using the following:
// 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)
这篇关于Golang在MongoDB中嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!