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
}热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志