Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-24947

Need a type conversion mechanism for booleans, ISODates, ObjectID

    XMLWordPrintable

    Details

    • Sprint:
      Query 12 (04/04/16), Query 13 (04/22/16), Query 15 (06/03/16)

      Description

      Syntax

      {$toISODate: <arbitrary expression>}
      {$toObjectId: <arbitrary expression>}
      {$toBoolean: <arbitrary expression>}
      

      Examples

      // Example 1
      > db.coll.insert([
        {_id: 0, x: 1},
        {_id: 1, x: 0}
      ]);
      > db.coll.aggregate([{
        $project: {
          boolean: {$toBoolean: "$x"}
        }])
      {_id: 0, boolean: true}
      {_id: 1, boolean: false}
       
      // Example 2
      > db.coll.insert([
        {_id: 0, x: "5769a41ba1db3f11dba6d4d3"}
      ]);
      > db.coll.aggregate([{
        $project: {
          objectID: {$toObjectID: "$x"}
        }])
      {_id: 0, objectID: ObjectId("5769a41ba1db3f11dba6d4d3")}
       
      // Example 3
      > db.coll.insert([
        {_id: 0, x: "2011-01-01"}
      ]);
      > db.coll.aggregate([{
        $project: {
          isoDate: {$toISODate: ["$x", "YYYY-MM-DD"]}
        }])
      {_id: 0, isoDate: ISODate("2011-11-11T00:00:00Z")}
      

      Notes

      • Calling $toBoolean on a boolean, $toISODate on an ISODate, or $toObjectID on an ObjectID, is a no-op.

      Errors

      • If the input is of a type or value that cannot be converted: e.g. $toBoolean should only convert 0/1, $toISODate and $toObjectID should only accept strings.

      Each of these operators will have an equivalent $coerceTo operator that optionally accepts a default value in cases where the vanilla version would error. In cases where no default it supplied, it would return the default value for the target type. "false" for booleans, unix epoch for dates, and an empty string for object identifiers.

      {$coerceToBoolean: "xxx"} // false
      {$coerceToBoolean: ["xxx", true]} // true
      {$coerceToBoolean: ["5.6abc"]} // false
       
      {$coerceToObjectID: ["5769a41ba1db3f11dba6d4d3"]} // ObjectID("5769a41ba1db3f11dba6d4d3")
      {$coerceToObjectID: ["x", 2]} // 2
       
      {$coerceToISODate: ["2011-11-11", "YYYY-MM-DD", ISODate("2014-11-11T00:00:00Z")]} // ISODate("2011-11-11T00:00:00Z")
      

        Attachments

          Issue Links

            Activity

              People

              Votes:
              13 Vote for this issue
              Watchers:
              30 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: