MongoDB: 在多个字段或数组上使用索引

MongoDB: using indexes on multiple fields or an array

我是 mongo

的新手

实体:

{
    "sender": {
        "id": <unique key inside type>,
        "type": <enum value>,
    },
    "recipient": {
        "id": <unique key inside type>,
        "type": <enum value>,
    },
    ...
}

我需要使用分页

通过查询 "find entities where sender or recipient equal to user from collection" 创建有效的搜索
foreach member in memberIHaveAccessTo:
    condition ||= member == recipient || member == sender

我已经阅读了一些关于 mongo 索引的内容。可能我的问题可以通过存储附加字段 "members" 来解决,该字段将是包含发件人和收件人的数组,然后在此数组上创建索引

  1. 是否可以用 monga 建立这样的索引?
  2. mongo 是创建类似索引的好选择吗?

关于查询和索引在查询字段上的应用问题中提出的问题的一些思考

(i) $or 和两个索引:

I need to create effective search by query "find entities where sender or recipient equal to user from collection...

您的查询将是这样的:

db.test.find( { $or: [ { "sender.id": "someid" }, { "recipient.id": "someid" } ] } )

对于在 "sender.id""recipient.id" 上定义的索引, 两个单独的索引 ,使用 $or 运算符的查询将使用这两个索引.

来自文档 ($or Clauses and Indexes):

When evaluating the clauses in the $or expression, MongoDB either performs a collection scan or, if all the clauses are supported by indexes, MongoDB performs index scans.

运行 带有 explain() 的查询并检查 查询计划 表明索引用于这两个条件。


(ii) 成员数组索引:

Probably my problem can be solve by storing addtional field "members" which will be array contains sender and recipient and then create index on this array...

有了 members 数组字段,查询将是这样的:

db.test.find( { members_array: "someid" } )

当在members_array字段上定义索引时,查询将使用该索引;生成的 查询计划 显示索引使用情况。请注意,在数组字段上定义的索引称为 Multikey Index.