2

I'm trying to convert timestamps in an array to dates with $dateFromString

Sample document which I'm trying to convert dates from:

{
    "_id" : ObjectId("5cbc5efc8af5053fd8bdca31"),
    "ticker" : "ticker",
    "currency" : "currency",
    "daily" : [ 
        {
            "timestamp" : "2019-04-18",
            "open" : "5.3300",
            "high" : "5.3300",
            "low" : "5.2000",
            "close" : "5.2700",
            "volume" : "6001"
        }, 
        {
            "timestamp" : "2019-04-17",
            "open" : "5.1500",
            "high" : "5.2900",
            "low" : "5.1500",
            "close" : "5.2700",
            "volume" : "37659"
        }, 
        {
            "timestamp" : "2019-04-16",
            "open" : "4.7100",
            "high" : "5.3000",
            "low" : "4.7100",
            "close" : "5.1500",
            "volume" : "112100"
        }
    ]
}

Aggregation query in pymongo:

db.test.aggregate([{
        '$project': {
            'daily.timestamp': {
                '$dateFromString': {
                    'dateString': '$daily.timestamp',
                    'format':  '%Y-%m-%d'
                }
            }
        }
    }])

This throws the following error:

pymongo.errors.OperationFailure: $dateFromString requires that 'dateString' be a string, found: array with value ["2019-04-18", "2019-04-17", "2019-04-16", "2019-04-15"....]

Is it even possible to apply $dateFromString to an array with hundreds of elements?

1 Answer 1

1

You can use the $map aggregation operator to apply $dateFromString to each element in the array:

db.test.aggregate([{
  "$project": {
    "ticker": 1,
    "currency": 1,
    "daily": {
      "$map": {
        "input": "$daily",
        "in": {
          "timestamp": { 
            "$dateFromString": {
              "dateString": '$$this.timestamp',
              "format":  '%Y-%m-%d'
            }
          },
          "open": "$$this.open",
          "high": "$$this.high",
          "low": "$$this.low",
          "close": "$$this.close",
          "volume": "$$this.volume"
        }
      }
    }
  }
}])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.