MongoDB索引和$或运算符

编程入门 行业动态 更新时间:2024-10-23 09:40:11
本文介绍了MongoDB索引和$或运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

很抱歉,如果之前有人问过这个问题。我找不到明确的答案。如果我的查询包含$或运算符,我可以在mongodb索引上查询吗?我的查询如下所示:

Sorry if this has been asked before. I couldn't find a definitive answer. Can I query on a mongodb index if my query contains the $or operator? My query looks something like this:

// find everything in the collection $cursor = $collection->find(array( '$or' => array( array('album_id' => array( '$in' => $this->my_album_ids ), 'type' => array( '$in' => array('like','comment') ) ), array( 'user_id' => (int)session_item('user_id'), 'type' => 'message', 'reply' => 'no' ) ), 'timestamp' => array('$gt' => (int)$since)))->sort(array('timestamp'=>-1))->skip($start)->limit($amount);

示例在PHP中,但我想这适用于任何语言。

The Example is in PHP, but I guess this is applicable to any language.

更新:

以下是我的索引,但上述查询不使用它们。不过我看起来是对的。

The following are my indexes, but the above query does not use them. It looks right to me though.

$collection->ensureIndex(array( 'album_id' => 1, 'type' => 1, 'timestamp' => -1, )); $collection->ensureIndex(array( 'user_id' => 1, 'type' => 1, 'reply' => 1, 'timestamp' => -1, ));

这是我的解释()

Array ( [cursor] => BasicCursor [nscanned] => 12 [nscannedObjects] => 12 [n] => 6 [scanAndOrder] => 1 [millis] => 0 [nYields] => 0 [nChunkSkips] => 0 [isMultiKey] => [indexOnly] => [indexBounds] => Array ( ) [allPlans] => Array ( [0] => Array ( [cursor] => BasicCursor [indexBounds] => Array ( ) ) ) [oldPlan] => Array ( [cursor] => BasicCursor [indexBounds] => Array ( ) ) )

推荐答案

是的,$或查询将根据需要使用索引。例如:

Yes, an $or query will use indexes as appropriate. For example :

> db.test.ensureIndex({a:1}) > db.test.ensureIndex({b:1}) > db.test.find({$or:[{a:1}, {b:2}]}).explain() { "clauses" : [ { "cursor" : "BtreeCursor a_1", "nscanned" : 0, "nscannedObjects" : 0, "n" : 0, "millis" : 0, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { "a" : [ [ 1, 1 ] ] } }, { "cursor" : "BtreeCursor b_1", "nscanned" : 0, "nscannedObjects" : 0, "n" : 0, "millis" : 1, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { "b" : [ [ 2, 2 ] ] } } ], "nscanned" : 0, "nscannedObjects" : 0, "n" : 0, "millis" : 1 }

更多推荐

MongoDB索引和$或运算符

本文发布于:2023-11-22 13:19:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   索引   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!