筛选包含对象数组的猫鼬文档

时间:2019-10-20 02:11:09

标签: node.js mongodb mongoose filter

我想知道如何使用猫鼬在MongoDB中检索文档,这些文档在对象数组中的“ done”属性均具有true值。 像这样的东西: 应该找到这个:

    _id : xxxx,
    step:
    [{name : "step1", done : true},
    {name : "step2", done : true},
    {name : "step3", done : true}
    {name : "step4", done : true}
    ]
    otherProperty : "random string ...",
    ...,
    __v : 0
------

这个应该被忽略

    _id : xxxx,
    step:
    [{name : "step1", done : true},
    {name : "step2, done : true},
    {name : "step3", done : false}
    {name : "step4", done : true}
    ]
    otherProperty : "random string ...",

谢谢

2 个答案:

答案 0 :(得分:0)

以下代码将从MongoDB集合中获取所有文档,遍历它们以检查哪些文档已成功完成所有步骤,然后打印已完成所有步骤的文档。

const mongoose = require( "mongoose" );
const Schema   = mongoose.Schema;
const Model    = mongoose.model;

const StepSchema = new Schema({
    step: [Object],
    name: String
});


Step = Model( "Step", StepSchema );

mongoose.connect( "mongodb://localhost:27017/chummy", { useNewUrlParser: true, useUnifiedTopology: true } );

Step.find( {}, (err, docs) => {  // Get all the documents from the COllection.

    docs.forEach(doc => {  // Select the documents one by one.

        let success = true; // Set a variable that will tell whether the document completed all the steps or not.

        doc.step.forEach( s => {  // Select each step one by one.
            if(!s.done == true) {  // Check if the step was done or not e.g. s.done = true
                success = false;    // If the step was not done, then change success to false.
                return; // Since a step failed, there's no need to continue checking the rest.
            }
        } );

        if(success) {     // Check if success is still true.
            console.log(doc);  // If all the steps were completed, success will stay true and the document will be logged.
        }

    });

} );

注意:这就是全部代码,并且这些代码已在带有NodeJS 10.16.3,NPM 6.9.0和Mongoose 5.7.5的Ubuntu 19.04 Desktop上进行了测试。

答案 1 :(得分:0)

以这种方式尝试

LIMIT AND OFFSET