0

In Mongo DB Getting Whole collection of date even if one is matched inside it.

Creating a new Collection with the below data:

db.details.insert({
    "_id": 1,
    "name": "johnson",
    "dates": [
        {"date": ISODate("2016-05-01")},
        {"date": ISODate("2016-08-01")}
    ]
})

Fetching Back:

db.details.find().pretty()

Output:

{
    "_id": 1,
    "name": "Johnson",
    "dates": [
        {"date": ISODate("2016-05-01T00:00:00Z")},
        {"date": ISODate("2016-08-01T00:00:00Z")}
    ]
}

So here there is a collection called dates inside another collection details.

Now I want to filter the date inside dates using Greater than and want the result showing "2016-08-01".

But when I search like the following:

db.details.find(
    {"dates.date": {$gt: ISODate("2016-07-01")}},
    {"dates.date": 1, "_id": 0}
).pretty()

Getting the Result as below, Its giving me the entire collection even if one date is matched in it:

{
    "dates": [
        {"date": ISODate("2016-05-01T00:00:00Z")},
        {"date": ISODate("2016-08-01T00:00:00Z")}
    ]
}

Please help in getting the Expected data, i.e.:

{
  "date": ISODate("2016-08-01T00:00:00Z")
}
Krunal
  • 77,632
  • 48
  • 245
  • 261

1 Answers1

0

You can use aggregate framework for this:

db.details.aggregate([
    {$unwind: '$dates'},
    {$match: {'dates.date': {$gt: ISODate("2016-07-01")}}}, 
    {$project: {_id: 0, 'dates.date': 1}}
]);

Another way (Works only for mongo 3.2):

db.details.aggregate([
    {$project: {
        _id: 0, 
        dates: {
            $filter: {
                input: '$dates', 
                as: 'item', 
                cond: {
                    $gte: ['$$item.date', ISODate('2016-08-01T00:00:00Z')]
                }
            }
        }
    }
}]);

To only return the date field:

db.details.aggregate([
    {$unwind: '$dates'},
    {$match: {'dates.date': {$gt: ISODate('2016-07-01')}}}, 
    {$group: {_id: '$dates.date'}}, 
    {$project: {_id: 0, date: '$_id'}}
]);

Returns:

{ 
  "date" : ISODate("2016-08-01T00:00:00Z") 
}
Krunal
  • 77,632
  • 48
  • 245
  • 261