Home > Mobile >  MongoDB conditional projection of fields on find()
MongoDB conditional projection of fields on find()

Time:01-16

I have a mongo query like so:

db.collection_a.find(
    {
        Time: { $gte: new Date(beginTime), $lte: new Date(endTime) },
    },
    {
        Value: 1,
        UpperBound: 1,
        LowerBound: 1,
        Time: 1,
    }
)

I would want the project field Value to return only when Time is between a certain range. For all other docs returned by the find query, I do not want the Value fields to be included in the result.

Is there a way I can do this?

CodePudding user response:

Maybe something like this:

 db.collection.aggregate([
   {
     "$project": {
      Time: 1,
       UpperBound: 1,
       LowerBound: 1,
       "Value": {
        "$cond": [
      {
        $and: [
          {
            $lt: [
              "$Time",
              ISODate("2015-05-18T16:00:00Z")
            ]
          },
          {
            $gt: [
              "$Time",
              ISODate("2013-05-18T16:00:00Z")
            ]
          }
        ]
      },
      "$Value",
      "$$REMOVE"
    ]
     }
    }
  }
])

Explained: You add $cond in the project stage for the Value key/value pair and based on provided date range it will set same value or it will remove the Value field if the Time is outside the range.

playground

  •  Tags:  
  • Related