Excluding "0" values from MongoDB Compass aggregation result

89 Views Asked by At

I'm performing an aggregation in MongoDB Compass, and I want to exclude the values of "0" from the result. Currently, my aggregation returns the following date value: "1948-12-08 00:00:00.000". How can I modify my aggregation to exclude these "0" values from the result?

Here's a picture attached of my current aggregation:

I've tried various approaches, such as using $match with $ne, but I haven't been successful in excluding the "0" values. Any guidance or suggestions would be greatly appreciated.

I expecting to get: "1948-12-08" the year, month and day.

1

There are 1 best solutions below

1
user20042973 On BEST ANSWER

In general, I'd say that storing dates (only) as string types is a mistake. It can, among other things, make querying and displaying the data more difficult.

That said, you can probably achieve your desired results using the $split operator (in conjunction with the $arrayElemAt operator). It might look something like this:

db.collection.aggregate([
  {
    "$addFields": {
      "date": {
        "$arrayElemAt": [
          {
            "$split": [
              "$date",
              " "
            ]
          },
          0
        ]
      }
    }
  }
])

Playground demonstration here.

You should prepend a $match stage to do whatever filtering you need to do.