让我们创建一个包含文档的集合-
> db.demo754.insertOne({"DateOfBirth":new Date("2000-05-03")}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9b2da930c785c834e56f") } > db.demo754.insertOne({"DateOfBirth":new Date("2010-01-21")}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9b34a930c785c834e570") } > db.demo754.insertOne({"DateOfBirth":new Date("2018-05-03")}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9b3da930c785c834e571") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo754.find();
这将产生以下输出-
{ "_id" : ObjectId("5eae9b2da930c785c834e56f"), "DateOfBirth" : ISODate("2000-05-03T00:00:00Z") } { "_id" : ObjectId("5eae9b34a930c785c834e570"), "DateOfBirth" : ISODate("2010-01-21T00:00:00Z") } { "_id" : ObjectId("5eae9b3da930c785c834e571"), "DateOfBirth" : ISODate("2018-05-03T00:00:00Z") }
以下是将出生日期转换为年龄的查询-
> db.demo754.aggregate( [ { ... $project: { ... date:"$DateOfBirth", ... StudentAge: { ... $divide: [{$subtract: [ new Date(), "$DateOfBirth" ] }, ... (365 * 24*60*60*1000)] ... } ... } ... } ] )
这将产生以下输出-
{ "_id" : ObjectId("5eae9b2da930c785c834e56f"), "date" : ISODate("2000-05-03T00:00:00Z"), "StudentAge" : 20.014896543093606 } { "_id" : ObjectId("5eae9b34a930c785c834e570"), "date" : ISODate("2010-01-21T00:00:00Z"), "StudentAge" : 10.288869145833333 } { "_id" : ObjectId("5eae9b3da930c785c834e571"), "date" : ISODate("2018-05-03T00:00:00Z"), "StudentAge" : 2.003937638984018 }