具有多个字段的Mongoose查询文档,包括子字段Mongodb

时间:2019-03-06 05:40:39

标签: javascript mongodb mongoose

嗨,我在mongodb中具有以下文档模型

架构为

const ProductionsSchema=new Schema({
        name: {type: String, required: true, unique: true},
        isActive: {type: Boolean, default: true},
        locations: [{
            name: {type: String},
            isActive : {type: Boolean, default: false}
        }],
        trackno: {type: String}
})
Productions:[{ 
       _id: 125,
        name: 'John Smith',
        locations: [{ name: 'Boston', isActive: true}]
        isActive: true,
        trackno: 2123
    }, 
        { 
       _id: 126,
        name: 'Moe Adam',
        locations: [{ name: 'Chicago', isActive: true}]
        isActive: true,
        trackno: 5663
    }, 
     { 
       _id: 126,
        name: 'Henry Noel',
        locations: [{ name: 'Houston', isActive: false}]
        isActive: true,
        trackno: 4552
    }, 
      { 
       _id: 128,
        name: 'Tim Johnson',
        locations: [{ name: 'Denver', isActive: true}]
        isActive: false,
        trackno: 6672
    }

]

我正在尝试找到两个isActive true的列表

Productions.find({"isActive" : true , "locations.isActive": true}, (err, list)=>{
      if(err){
            callback(err);
            }
            callback(null, list)
        })

我正在尝试编写查询,因此isActive均为true。在上面的示例数据中,答案中仅应包含前两个记录。但是我一直在获取所有记录,即使是带有'false'的记录,我甚至还在location.isActive上尝试了$ elemMatch。 请让我知道如何解决此问题,以便仅获得两个isActive都只包含真实值的结果。

1 个答案:

答案 0 :(得分:0)

如原始评论所述,您唯一需要的查询条件是:

{ isActive: true, "locations.isActive": true }

这是一个基本的AND条件,您不需要任何特殊的运算符就可以验证数组中任何位置的单个属性是否满足条件。

由于这完全符合预期,所以我只能考虑向您显示完整的工作清单,以此作为基础来确定您在做的事情是否与众不同,从而使您无法获得与预期相同的结果。

const { Schema } = mongoose = require('mongoose');

const uri = 'mongodb://localhost:27017/productions';
const opts = { useNewUrlParser: true };

mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('debug', true);

const productionSchema = new Schema({
  name: String,
  isActive: { type: Boolean, default: true },
  locations: [{
    name: String,
    isActive: { type: Boolean, default: false }
  }],
  trackno: Number
})

const Production = mongoose.model('Production', productionSchema);

const data =
[
    {
        name: 'John Smith',
        locations: [{ name: 'Boston', isActive: true}],
        isActive: true,
        trackno: 2123
    },
        {
        name: 'Moe Adam',
        locations: [{ name: 'Chicago', isActive: true}],
        isActive: true,
        trackno: 5663
    },
     {
        name: 'Henry Noel',
        locations: [{ name: 'Houston', isActive: false}],
        isActive: true,
        trackno: 4552
    },
    {
        name: 'Tim Johnson',
        locations: [{ name: 'Denver', isActive: true}],
        isActive: false,
        trackno: 6672
    }
];

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {
    const conn = await mongoose.connect(uri, opts);

    // clean data
    await Promise.all(
      Object.entries(conn.models).map(([k, m]) => m.deleteMany())
    );

    // set up
    await Production.insertMany(data);

    // Query
    let query = { isActive: true, "locations.isActive": true };
    let results = await Production.find(query);

    log(results);


  } catch(e) {
    console.error(e)
  } finally {
    mongoose.disconnect()
  }

})()

输出两个预期文档:

Mongoose: productions.deleteMany({}, {})
Mongoose: productions.insertMany([ { isActive: true, _id: 5c7f7e9367daed19d6773e9b, name: 'John Smith', locations: [ { isActive: true, _id: 5c7f7e9367daed19d6773e9c, name: 'Boston' } ], trackno: 2123, __v: 0 }, { isActive: true, _id: 5c7f7e9367daed19d6773e9d, name: 'Moe Adam', locations: [ { isActive: true, _id: 5c7f7e9367daed19d6773e9e, name: 'Chicago' } ], trackno: 5663, __v: 0 }, { isActive: true, _id: 5c7f7e9367daed19d6773e9f, name: 'Henry Noel', locations: [ { isActive: false, _id: 5c7f7e9367daed19d6773ea0, name: 'Houston' } ], trackno: 4552, __v: 0 }, { isActive: false, _id: 5c7f7e9367daed19d6773ea1, name: 'Tim Johnson', locations: [ { isActive: true, _id: 5c7f7e9367daed19d6773ea2, name: 'Denver' } ], trackno: 6672, __v: 0 } ], {})
Mongoose: productions.find({ isActive: true, 'locations.isActive': true }, { projection: {} })
[
  {
    "isActive": true,
    "_id": "5c7f7e9367daed19d6773e9b",
    "name": "John Smith",
    "locations": [
      {
        "isActive": true,
        "_id": "5c7f7e9367daed19d6773e9c",
        "name": "Boston"
      }
    ],
    "trackno": 2123,
    "__v": 0
  },
  {
    "isActive": true,
    "_id": "5c7f7e9367daed19d6773e9d",
    "name": "Moe Adam",
    "locations": [
      {
        "isActive": true,
        "_id": "5c7f7e9367daed19d6773e9e",
        "name": "Chicago"
      }
    ],
    "trackno": 5663,
    "__v": 0
  }
]