MongoDB 多对多搜索
这是我的收藏:(多对多)
演员:
{
_id: 1,
name: "Name 1"
}
电影:
{
_id: 1,
name: "The Terminator",
production_year: 1984,
actors: [
{
actors_id: 1,
role_id : 1
},
{
actors_id: 2,
role_id : 1
}
]
}
我无法获取某些电影的演员列表,
当我有这个时,这不是问题:
{
_id: 1,
name: "The Terminator",
production_year: 1984,
actors: [1,2,3,4,5] (actors id's)
}
var a = db.movies.findOne(name:"The Terminator").actors
db.actors.find({"_id":{$in:a}})
但是,我怎样才能用上面的结构来制作它:
如果,我这样做 var a = db.movies.findOne(name:"The Terminator").actors
它会返回给我这个:
[
{
actors_id: 1,
role_id : 1
},
{
actors_id: 2,
role_id : 1
}
]
How do I get only this in array [1,2] (actors_id ) 获取名称演员(含美元)
谢谢, 佐兰
this is my collections: (many-to-many)
actors:
{
_id: 1,
name: "Name 1"
}
movies:
{
_id: 1,
name: "The Terminator",
production_year: 1984,
actors: [
{
actors_id: 1,
role_id : 1
},
{
actors_id: 2,
role_id : 1
}
]
}
I can't get a list of actors for some movie
it is not a problem when I have this:
{
_id: 1,
name: "The Terminator",
production_year: 1984,
actors: [1,2,3,4,5] (actors id's)
}
var a = db.movies.findOne(name:"The Terminator").actors
db.actors.find({"_id":{$in:a}})
but, how can I make it with this above structure:
if, I do this var a = db.movies.findOne(name:"The Terminator").actors
it returns me this:
[
{
actors_id: 1,
role_id : 1
},
{
actors_id: 2,
role_id : 1
}
]
How do I get only this in array [1,2] (actors_id) to get the names of actors (with $in)
Thanks,
Zoran
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不知道。在 MongoDB 中,您总是查询文档,因此您必须确保您的架构能够通过查询特定文档来获取所需的所有信息。 MongoDB 中没有类似连接/查看的功能。
在这种情况下,非规范化通常是最合适的选择。您的架构看起来像是为传统关系数据库设计的,您必须尝试放弃关系数据附带的一些架构设计原则。
具体来说,对于您的示例,您可以将演员姓名添加到嵌入数组中,以便在查询电影后获得该信息。
最后,考虑一下您是否使用了正确的工具来完成您需要做的事情。人们常常认为 MongoDB 是“快速的 MySQL”,这是完全错误的。文档数据库与 RDBMS 甚至 k/v 存储非常不同。如果您有大量相关数据,请使用 RDBMS。
You don't. Within MongoDB you always query for documents so you have to make sure your schema is such that you can get all the information you need by querying for specific documents. There is no join/view like functionality in MongoDB.
Denormalization is usually the most appropriate choice in such cases. Your schema looks like it's designed for a traditional relational database and you will have to try and let go of some of the schema design principles that come with relational data.
Specifically for your example you could add the actor name to the embedded array so you have that information after querying for the movie.
Finally, consider if you're using the right tool for what you need to do. Too often people think of MongoDB is a "fast MySQL" which is entirely wrong. Document databases are very different to RDBMS and even k/v stores. If you have a lot of related data use an RDBMS.
db.movies.findOne(name:"The Terminator").actors
中的变量 a 是文档数组,因此您必须将其设为整数 (ids) 数组variable a in
db.movies.findOne(name:"The Terminator").actors
is an array of documents, so you'd have to make it an array of integers (ids)