mongodb - 按相对数组元素位置查找文档

标签 mongodb mongodb-query aggregation-framework

我想在数组中搜索一个字段,想知道该字段在数组中的索引是什么,是否可以找到它? 示例:

doc1: {id:123, hobby:['chess','cards','dance']}
doc2: {id:123, hobby:['cards','dance','chess']}

我只想搜索具有 chesscards 但只有在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/

相关文章:

node.js - 使用 mongojs Node 中的不同失败

javascript - 如何通过异步 Mongo 调用设置 React State?

mongodb - 使用限制时使用 MongoDB 获取总文档数

node.js - 具有连接的近几何

mongodb - 通过 mod(ObjectId) 选择文档的一部分

mongodb - Meteor 中的平均聚合查询

java - 如何使用 FindIterable<Document> 使用 java 从 mongodb 获取特定字段

Mongodb插入没有_id字段的文档

javascript - 使用聚合以及跳过和限制时获取文档总数

mongodb - 如何使用 mongodb 聚合返回字符串数组