MongoDB:如何在文档数组元素中搜索



我相信对于大多数Mongo用户来说,这是一个微不足道的问题,但是,我很不幸地找到了正确的答案。我有一系列文件,例如

{
  _id:"2a1fd96c-73c5-49e1-a8ca-bd03a20c0197",
  timestamp:1519725979178,
  storeID:"xxx",
  unitID: "yyy",
  status:[1, 0, 1, 0],
  _rev:"1-8019f22bf26b4d6cb99ae5460b3e0c65"
}

我需要找到符合以下条件的所有文件:

storeID = "xxx" AND unitID = "yyy" AND status[2] = 1

我的过滤器条目适用于指南针

{'status.2': 1,storeID:'xxx',unitID:'yyy'}

但是当我尝试将其转换为 Js 代码时

Model.find({'status.2': 1,storeID:'xxx',unitID:'yyy'})

不返回任何内容。

在拔掉头发几个小时后,我解决了问题。筛选查询 {'status.2':1,storeID:'xxx',unitID:'yyy'}{'status.2':{$eq:1},storeID:'xxx',unitID:'yyy'}其实还可以。

不幸的是,我将.find()与 Model 一起使用,而不是在集合范围内调用它:

let mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    MyShema = new Schema({/* definition */}),
    Model = mongoose.model('MyShema'),
    filter = {'status.2':1,storeID:'xxx',unitID:'yyy'};

// BEFORE
let cursor = Model.find(fd); //returns total=0

// AFTER
let cursor = Model.collection.find(fd); //returns total=80
cursor.count()
    .then(total=>console.log('total',total))
    .catch(error=>console.log(error));

当我从过滤选项中删除'status.2':1时,奇怪的是,光标的两个实例都返回了相同数量的文档。这样做的原因太可悲了 - status在 Schema 中声明为 String,而它显然应该是Array的!

最新更新