“仅当”要索引的字段之一具有特定值时,是否可以索引集合中的某些文档?
让我用一个例子来解释:
集合“posts”有数百万个文档,ALL 定义如下:
{ "network": "network_1", "blogname": "blogname_1", "post_id": 1234, "post_slug": "abcdefg" }
Let's assume that the distribution of the post is equally split on network_1 and network_2
My application OFTEN select the type of query based on the value of "network" (although sometimes I need the data from both networks):
For example:
www.test.it/network_1/blog_1/**postid**/1234/
-> db.posts.find ({network: "network_1" blogname "blog_1", post_id: 1234})
www.test.it/network_2/blog_4/**slug**/aaaa/
-> db.posts.find ({network: "network_2" blogname "blog_4" post_slug: "yyyy"})
我可以创建两个单独的索引(network/blogname/post_id 和 network/blogname/post_slug),但我会浪费大量 RAM,因为索引中 50% 的数据永远不会被使用。
有没有办法创建一个“过滤”的索引?
例子: (注意WHERE参数)
db.posts.ensureIndex ({network: 1 blogname: 1, post_id: 1}, {where: {network: "network_1"}})
db.posts.ensureIndex ({network: 1 blogname: 1, post_slug: 1}, {where: {network: "network_2"}})
最佳答案
事实上,在 MongoDB 3.2+ 中这是可能的,他们称之为 partialFilterExpression,您可以在其中设置基于将创建哪个索引的条件。
示例
db.users.createIndex({ "userId": 1, "project": 1 },
{ unique: true, partialFilterExpression:{
userId: { $exists: true, $gt : { $type : 10 } } } })
请参阅Partial Index文档
关于MongoDB "filtered"索引 : is it possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18505035/