仅搜索月份和日期的 MongoDB 查询?
要仅搜索月份和日期,请使用聚合框架。
让我们首先使用文档创建一个集合 -
> db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2019-04-27")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbcaeef71edecf6a1f6b2") } > db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2018-04-30")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbcb7ef71edecf6a1f6b3") } > db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2018-04-27")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbcbcef71edecf6a1f6b4") } > db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2016-04-27")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbdaaef71edecf6a1f6b5") }
使用 find() 方法显示集合中的所有文档 -
> db.monthAndDayDemo.find();
输出
{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "LoginDate" : ISODate("2019-04-27T00:00:00Z") } { "_id" : ObjectId("5cefbcb7ef71edecf6a1f6b3"), "LoginDate" : ISODate("2018-04-30T00:00:00Z") } { "_id" : ObjectId("5cefbcbcef71edecf6a1f6b4"), "LoginDate" : ISODate("2018-04-27T00:00:00Z") } { "_id" : ObjectId("5cefbdaaef71edecf6a1f6b5"), "LoginDate" : ISODate("2016-04-27T00:00:00Z") }
以下是仅搜索月份和日期的查询 -
{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "LoginDate" : ISODate("2019-04-27T00:00:00Z") } > db.monthAndDayDemo.aggregate( { "$project": { "m":{"$month":"$LoginDate"}, "d": { "$dayOfMonth":"$LoginDate" } }}, { "$match":{ "m": 4, "d": 27 } } );
输出
{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "m" : 4, "d" : 27 } { "_id" : ObjectId("5cefbcbcef71edecf6a1f6b4"), "m" : 4, "d" : 27 } { "_id" : ObjectId("5cefbdaaef71edecf6a1f6b5"), "m" : 4, "d" : 27 }
广告