After analyzing the data provided, I am seeking a way to retrieve objects from the od array based on specific conditions. Additionally, I aim to extract the em and name fields as well.
Although I lack extensive knowledge on MongoDB's aggregate functionality. Therefore, assistance is needed to resolve my current dilemma.
{
_id: 1,
em: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e4e7e6c5b4b7f6abebe0f1">[email protected]</a>',
name: 'NewName',
od:
[
{
"oid": ObjectId("1234"),
"ca": ISODate("2016-05-05T13:20:10.718Z")
},
{
"oid": ObjectId("2345"),
"ca": ISODate("2016-05-11T13:20:10.718Z")
},
{
"oid": ObjectId("57766"),
"ca": ISODate("2016-05-13T13:20:10.718Z")
}
]
},
{
_id: 2,
em: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f4a0f5d6eeefecb8f8f3e2">[email protected]</a>',
name: 'NewName2',
od:
[
{
"oid": ObjectId("1234"),
"ca": ISODate("2016-05-11T13:20:10.718Z")
},
{
"oid": ObjectId("2345"),
"ca": ISODate("2016-05-12T13:20:10.718Z")
},
{
"oid": ObjectId("57766"),
"ca": ISODate("2016-05-05T13:20:10.718Z")
}
]
}
My attempts with $match, $project, and $unwind of aggregate have been made to achieve the desired outcome. The query used is as follows:
db.collection.aggregate([
{
$match : {
"od.ca": {
'$gte': '10/05/2016',
'$lte': '15/05/2016'
}
}
},
{
$project:{
_id: '$_id',
em: 1,
name: 1,
od: 1
}
},
{
$unwind: "$od"
},
{
$match: {
"od.ca": {
'$gte': '10/05/2016',
'$lte': '15/05/2016'
}
}
}])
The result obtained includes em, name, and an od array with one object from od, indicating multiple records for the same email ID.
// Result Output Examples
{
_id: 1,
em: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899bacbc889d4949f8e">[email protected]</a>',
name: 'NewName',
od:
[
{
"oid": ObjectId("57766"),
"ca": ISODate("2016-05-13T13:20:10.718Z")
}
]
}
{
_id: 1,
em: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066764654637347528686372">[email protected]</a>',
name: 'NewName',
od:
[
{
"oid": ObjectId("2345"),
"ca": ISODate("2016-05-11T13:20:10.718Z")
}
]
}
To achieve the desired output format where each unique email ID contains all matching objects in the od array, modifications may be required in the query structure. An example of the expected result is shown below:
// Desired Output Format Example
{
_id: 1,
em: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d7d6f58487c69bdbd0c1">[email protected]</a>',
name: 'NewName',
od:
[
{
"oid": ObjectId("2345"),
"ca": ISODate("2016-05-11T13:20:10.718Z")
},
{
"oid": ObjectId("57766"),
"ca": ISODate("2016-05-13T13:20:10.718Z")
}
]
}
If the query is not generating the expected results, further analysis or adjustments within the query structure are recommended to achieve the desired outcome. Any insights or guidance on improving the query would be greatly appreciated.