-
Type: Improvement
-
Resolution: Duplicate
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Aggregation Framework
-
Query
-
Query 12 (04/04/16), Query 13 (04/22/16), Query 15 (06/03/16)
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")
- duplicates
-
SERVER-33510 Add shorthand syntax for $convert
- Closed
- is related to
-
SERVER-22781 Allow $lookup between ObjectId (_id.str) and string
- Closed
- related to
-
SERVER-9406 Allow treating ObjectId type as date in $project phase
- Closed
-
SERVER-11400 Need a type conversion mechanism to convert between strings and numbers
- Closed
-
SERVER-29512 Convert an ObjectId to a hex string in aggregation pipeline stages
- Closed