简体   繁体   中英

How filter sub sub document in MongoDB

Hello I am working with the full Stack 'MEAN' and i have a data structure in MongoDB as indicated below:

var ExpenseSchema = new Schema({
    date: {
        type: Date,
        default: Date.now,
        required: 'Ingrese la fecha del comprobante'
    },
    supplier: {
        type: Schema.ObjectId,
        ref: 'Supplier',
    },
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});


var SupplierSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Ingrese la Razon Social del Proveedor',
        trim: true
    },
    category: {
        type: Schema.ObjectId,
        ref: 'Category',
    },
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

var CategorycompraSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Rubrocompra name',
        trim: true
    },
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

Each 'Expense' has a 'Supplier' and each supplier has a 'Category'

I need to query so that I filter all 'Expenses' in a particular category. Someone could tell me how this can be done with MongoDB or mongoose?

That is an important case in mongodb, aggregations in mongodb is the right approach to solve this. You need to $unwind the supplier array and then category array and then use $group to put it back together:

My solution may differ depending upon your requirement, but this is something you have to do:

db.test.aggregate(
    { $match: {...}},   //match query 
    { $unwind: '$supplier'},
    { $unwind: '$supplier.category'},
    { $match: {supplier.category.a: ...}},      //match query after unwinding of supplier and category
    { $group: {_id: '$_id', ...})

It will first unwind the supplier array and then unwind category array

But since you are also using mongoose, you can use plain JavaScript. You can fetch all expenses and then loop through them and obtain your result

Expense.find().then(function(expenses) {
    expenses.forEach(function(suppliers){
        suppliers.forEach
        ...
    })
})

Although this javascript way would increase effort in single threaded enviroment(node js), but still it comes in handy for some typical mongodb queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM