简体   繁体   中英

Mongo DB query not returning desired result for aggregate $match but working correctly for .find()

Hi I am trying write code that returns objects from a mongo db, with the criteria being they must have a certain name and be above a certain age. This logic will be used for paging further on.

I need to implement this query for both.find() and aggregate $match. It returns the desired result for.find but returning an empty array for aggregate $match. Can someone tell me where I'm going wrong?

*name, lastAge and lastId will all be query parameters, lastAge will get parsed to an Int etc.

const query = {
        name: name
    };
    
    if (lastAge) {
        const ageQuery = {};
        ageQuery[age] = {'$gt': lastAge };
    
        if (lastId) {
            query.$or = [ageQuery, { _id: { '$gt': lastId } }]
        } else {
            query = {
                ...query,
                ... ageQuery
            }
        }
    }

Person DB objects

            [{
                "_id": "152asbasfb56",
                "name": "test",
                "company": "company1",
                "age":1
            },
            {
                "_id": "123gf77293ewf",
                "name": "test",
                "company": "company2",
                "age": 2
            },
            {
                "_id": "536gfjdbe8000",
                "name": "testName",
                "company": "company3",
                "age":3
            }]

.find() implementation

const people = await Person.find(query); //returns desired documents

aggregate $match

const people = await Person.aggregate([
        {
            $match: query                 //returns []
        }]);

If you use object Id in your query you need use mongoose.Types.ObjectId(obj_id) instead obj_id In find() you can use obj_id but not in aggregate

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