월과 일만 검색하려면 집계 프레임워크를 사용하세요.
먼저 문서로 컬렉션을 만들어 보겠습니다. −
> 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 }