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

15 thoughts on “Unable to process data from MongoDB”

  1. In MongoDB, you can use dot notation to specify query conditions for field in a document at a particular index of the array like details.0.somAnotherDate but it will not work in projection as mentioned here:

    you cannot project specific array elements using the array index; e.g. { "instock.0": 1 } projection will not project the array with the first element.

    To get somAnotherDate field of the first item in details, you can use $arrayElemAt. For example:

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

Leave a Comment