Unable to process data from MongoDB

Suppose I have a schema as: Model1.js:

const mongoose = require('mongoose');

const bookSchema = mongoose.Schema({
    someDate: { type: Date },
})

Based on this schema I have stored data in mongoDB as:

{[
    "someDate" : ISODate("2021-02-16T06:42:52.652Z"),
}]

when I try to filter it based on month I get the result as:

const info = await Model1.aggregate([...some other matchning parameters,{ $project: { month: { $month: "$someDate" } } }]).exec();

//O/p: [{  month: 2 }]

Now let’s suppose I have another schema as : Model2.js:

 const mongoose = require('mongoose');

const desktop = mongoose.Schema({
    details: [{
        somAnotherDate: { type: Date },
    }]
})

And when I try to filter it:

 const info = await Model1.aggregate([...some other matchning parameters,{ $project: { month: { 
             $month: "$details[0].somAnotherDate" } } }]).exec();

  // O/p: [{month: null }]

So what is causing the issue and it is unable to process the date?

Type of Date saved in both condition is also same, so what is causing the issue. Or I cannot fetch the value in such way while querying MongoDB?

I tried:

const info = await Model1.aggregate([...some other matchning parameters,{ 
$project: { month: $unwind:"$details", {  $month: somAnotherDate" } } }]).exec();

But this is not allowed as it’s throwing error.

Please do let me know what all methods can I apply.

EDIT:

Say I have data saved as

{details:[{"someDate" : ISODate("2021-02-16T06:42:52.652Z"),},
          {"someDate" : ISODate("2021-03-16T06:42:52.652Z")}]}

As per provided answer by @Cuong Le Ngoc:

const info = await Model1.aggregate([
  ...some other matchning parameters,
  { 
    $project: { 
      month: { 
         $month: { $arrayElemAt: ["$details.somAnotherDate", 0] } 
      } 
    } 
  }
]).exec();

and we can get the o/p as:

// O/p: [{month: 2 }]

But here we processed assuming we have only one element inside details array , but what if we have multiple elements. how can I iterate using the method provided as it only deals with one element.

Expected o/p as:

O/p: [{month: 2 },{month: 3 }]

Please let me know if you need any more details

16 thoughts on “Unable to process data from MongoDB”

  1. 295671 115979Hi my friend! I want to say that this post is awesome, nice written and include almost all significant infos. Id like to see more posts like this . 339132

    Reply

Leave a Comment