V
V
Vitaly the Wise2018-01-03 17:11:50
MongoDB
Vitaly the Wise, 2018-01-03 17:11:50

How to write a mongoDB aggregate query?

Hello. I am writing a query with grouping on mongodb now. There are some problems. The request itself:

const StatsSchema = mongoose.Schema({
    advertiser: {
        type: ObjectId,
        ref: 'Advertiser',
        required: true
    },
    offer: {
        type: ObjectId,
        ref: 'Offer',
        required: true
    },
    spent: {
        type: Number,
        required: true
    },
    revenue: {
        type: Number,
        required: true
    },
    date: {
        type: String,
        required: true
    },
    user: {
        type: ObjectId,
        ref: 'User',
        required: true
    }
});

module.exports.getMyDailyStats = (advertiser, user, callback) => {
  Stats.aggregate([
        {
            $match: {
                $and: [{ advertiser: advertiser }, { user: user }]
            }
        },
        { 
            $group: { 
                _id: "$offer",
                stats: {
                    $push: {
                        spent: '$spent',
                        revenue: '$revenue',
                        date: '$date'
                    }
                }

            },
        }
    ], callback);
}

Sample document in the database (mLab)
{
    "_id": {
        "$oid": "5a49490c79007365f64b44c4"
    },
    "advertiser": {
        "$oid": "5a49024a87aec437bdd6d976"
    },
    "offer": {
        "$oid": "5a49046954383f38ab383351"
    },
    "spent": 500,
    "revenue": 800,
    "date": "2017-12-25T22:00:00.000Z",
    "user": {
        "$oid": "5a46969521d5214eada6ca0d"
    },
    "__v": 0
}

When the request is completed, it returns an empty array, but there are such values ​​in the database. And I also want to return its name (populate) instead of the id of the offer. Help me please. Thanks

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question