MongoDB "filtered"索引 : is it possible?

标签 mongodb indexing

“仅当”要索引的字段之一具有特定值时,是否可以索引集合中的某些文档?

让我用一个例子来解释:

集合“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/

相关文章:

需要Mysql优化帮助

php - 如何正确索引以下内容?

c# - MongoDb 3.4 C# 驱动程序 - 如何使用 C# 驱动程序创建等效聚合查询

c - 使用 Eclipse 在 Mac 上找不到 mongo c libs

node.js - Mongoose 中的模式关联

mongodb - 如何在更新大型集合时禁用 mongodb 索引

java - 我的 java 应用程序抛出一个异常,显示 Invalid BSON field name Name

mongodb - $sum 有多个条件

python - 返回姓名首字母大写的函数

sql - 如何将索引与数据分开存储在Azure上?