我想在数组中搜索一个字段,想知道该字段在数组中的索引是什么,是否可以找到它? 示例:
doc1: {id:123, hobby:['chess','cards','dance']}
doc2: {id:123, hobby:['cards','dance','chess']}
我只想搜索具有
chess
和cards
但只有在card
之前有chess
的。所以万一 doc1
.
最佳答案
您可以使用 $where
来做到这一点运算符,将其与 $all
耦合运营商保持合理的性能:
db.test.find({
// Find all the docs where hobby contains both 'cards' and 'chess'
hobby: {$all: ['cards', 'chess']},
// Of those, run this $where query that evaluates the indexes of the matched elements
$where: "this.hobby.indexOf('cards') > this.hobby.indexOf('chess')"
})
添加关于爱好
的索引以获得最佳性能。
关于mongodb - 按相对数组元素位置查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36457677/