MongoDB 查询获取特定月份 | 年份(不含日期)?


你可以结合聚合框架和 $month 投影运算符。我们先使用文档创建一个集合 -

> db.specificMonthDemo.insertOne({"StudentName":"Larry","StudentDateOfBirth":new ISODate('1995-01-12')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9a9ca8f1d1b97daf71819")
}
> db.specificMonthDemo.insertOne({"StudentName":"Chris","StudentDateOfBirth":new ISODate('1999-12-31')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9a9db8f1d1b97daf7181a")
}
> db.specificMonthDemo.insertOne({"StudentName":"David","StudentDateOfBirth":new ISODate('2000-06-01')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9a9ee8f1d1b97daf7181b")
}

以下是通过 find() 方法显示集合中所有文档的查询 -

> db.specificMonthDemo.find().pretty();

将产生以下输出 -

{
   "_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
   "StudentName" : "Larry",
   "StudentDateOfBirth" : ISODate("1995-01-12T00:00:00Z")
}
{
   "_id" : ObjectId("5cb9a9db8f1d1b97daf7181a"),
   "StudentName" : "Chris",
   "StudentDateOfBirth" : ISODate("1999-12-31T00:00:00Z")
}
{
   "_id" : ObjectId("5cb9a9ee8f1d1b97daf7181b"),
   "StudentName" : "David",
   "StudentDateOfBirth" : ISODate("2000-06-01T00:00:00Z")
}

以下是获取特定月份 | 年份,但不是日期的查询 -

> db.specificMonthDemo.aggregate([ {$project: {StudentName: 1, StudentDateOfBirth:
   {$month: '$StudentDateOfBirth'}}}, {$match: {StudentDateOfBirth: 01}} ]).pretty();

将产生以下输出 -

{
   "_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
   "StudentName" : "Larry",
   "StudentDateOfBirth" : 1
}

更新时间:30-Jul-2019

627 次浏览

开启您的职业生涯

完成课程即可获得认证

快速入门
广告
© . All rights reserved.