I don’t know how correctly I formulated the question. I need to execute a query on both the values of the collection and the values of the referenced objects.
The original collection looks like this:
{
"houses": [
{
"_id": "5fe72f0b4fd2c131bcc7dae0",
"name": "John",
"district": "Texas",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504c",
"kind": "developer",
"group": "facebook"
}
]
},
{
"_id": "5fe72f0b4fd2c131bcc7dadf",
"name": "Michael",
"district": "Texas",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504b",
"kind": "advertiser",
"group": "instagram"
}
]
},
{
"_id": "5fe72f0b4fd2c131bcc7dade",
"name": "Frank",
"district": "Washington",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504a",
"kind": "developer",
"group": "school"
}
]
}
]
}
When executing a query that meets the condition district == "Texas"
, I need to get the following result:
{
"houses": [
{
"_id": "5fe72f0b4fd2c131bcc7dae0",
"name": "John",
"district": "Texas",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504c",
"kind": "developer",
"group": "facebook"
}
]
},
{
"_id": "5fe72f0b4fd2c131bcc7dadf",
"name": "Michael",
"district": "Texas",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504b",
"kind": "advertiser",
"group": "instagram"
}
]
}
]
}
Under this condition: kind == "developer"
, get the following result:
{
"houses": [
{
"_id": "5fe72f0b4fd2c131bcc7dae0",
"name": "John",
"district": "Texas",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504c",
"kind": "developer",
"group": "facebook"
}
]
},
{
"_id": "5fe72f0b4fd2c131bcc7dade",
"name": "Frank",
"district": "Washington",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504a",
"kind": "developer",
"group": "school"
}
]
}
]
}
And for a query that satisfies the condition: district == "Texas" && kind == "developer"
, get the result:
{
"houses": [
{
"_id": "5fe72f0b4fd2c131bcc7dae0",
"name": "John",
"district": "Texas",
"events": [
{
"_id": "5fe73e91ede45b3d2eca504c",
"kind": "developer",
"group": "facebook"
}
]
}
]
}
The query should be executed using mongoose inside the express route, and should be universal, processing a different set of request parameters:
router.get('/report', (req, res) => {
let params = {};
let { district, kind } = req.headers;
if (district) params["district"] = district;
if (kind) params["kind"] = kind;
// Here should be the query
});
The House
model refs to Event
:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const HouseSchema = new Schema({
name: String,
district: String,
events: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Event'
}]
});
module.exports = mongoose.model('House', HouseSchema);
I am learning MongoDB and aggregation, but I don’t know so deeply all its functions. Please tell me how to correctly execute such a request in the traditional way? I will be very grateful!
Advertisement
Answer
db.collection.aggregate([
{$unwind:"$houses"},
{$match:{"houses.district":"Texas","houses.events":{$elemMatch:{"kind":"developer"}}}},
{$group:{
_id:null,
houses:{$push:"$houses"}
}},
{$project:{_id:0}}])