MongoDB Aggregate with Pymongo 관련

2020. 2. 28. 00:04서버 프로그래밍

전체 기사에서 24시간 이내에 생성된 기사들에 대해서 카테고리별 개수를 구해서 출력하는 쿼리문

db.articles.aggregate(
 	{
 		$project:{
 			date:{
 				$dateFromString:{
 					dateString:'$created_at',
 					format:'%Y-%m-%d %H:%M:%S'
 				}
 			},
            category:1
 		}
 	},
 	{
 		$match:{
 			date:{
 				$gte:new Date(new Date().getTime()-(1000*60*60*24))
 			}
 		}
 	},
 	{
 		$group:{
 			_id:{
                category: '$category'
            }, 
 			total:{
 				$sum:1
 			}
 		}
 	},
 	{
 		$sort:{
 			total:-1
 		}
 	}
)

 

문자열로 저장되어 있는 날짜를 날짜 타입으로 바꾸는 방법

{ $dateFromString: {
     dateString: <dateStringExpression>,
     format: <formatStringExpression>,
     timezone: <tzExpression>,
     onError: <onErrorExpression>,
     onNull: <onNullExpression>
} }

https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/

 

$dateFromString (aggregation) — MongoDB Manual

timezone Optional. The time zone to use to format the date. Note If the dateString argument is formatted like ‘2017-02-08T12:10:40.787Z’, in which the ‘Z’ at the end indicates Zulu time (UTC time zone), you cannot specify the timezone argument. allows for

docs.mongodb.com

현재 날짜를 기준으로 검색 쿼리를 사용하는 방법

db.collectionName.aggregate({
  "$project": {
    "year": {
      "$year": "$date"
    },
    "month": {
      "$month": "$date"
    },
    "day": {
      "$dayOfMonth": "$date"
    }
  }
}, {
  "$match": {
    "year": new Date().getFullYear(),
    "month": new Date().getMonth() + 1, //because January starts with 0
    "day": new Date().getDate()
  }
})

https://stackoverflow.com/questions/30772285/mongodb-find-query-comparision-with-currentdate

 

MongoDB find Query comparision with CurrentDate

I want to fetch current day documents from a MongoDB collection. My documents look like this: { "_id" : ObjectId("55743941789a9abe7f4af3fd"), "msisdn" : "9xxxxxxxxxx", "act_date" :

stackoverflow.com

MongoDB 콘솔에서 Javascript의 Date 타입으로 날짜 연산을 한다

//24시간 전
new Date(new Date().getTime() - (1000*60*60*24))

https://heeestorys.tistory.com/744

 

[Javascript] 자바스크립 날짜/시간 더하기,빼기,차 - get, getTime()

자바스크립 날짜/시간 더하기,빼기,차 1. 더하기/빼기 - get메소드로 값을 구한 후 수정된 값을 set한다 var date = new Date('2016/12/25 08:23:13'); console.log(date); console.log(date.toLocaleString()); d..

heeestorys.tistory.com

pymongo로 연동시 datetime과 timedelta를 이용하여 날짜 연산을 수행할 수 있다.

# convert your date string to datetime object
start = datetime(2014, 9, 24, 7, 51, 04)
end = datetime(2014, 9, 24, 7, 52, 04)

inoshare.find( {'id_no': 1, 'datahora': {'$lt': end, '$gte': start}, 'porta': 'A0'})
<pymongo.cursor.Cursor at 0x7f9aafd64a90>

inoshare.find_one( {'id_no': 1, 'datahora': {'$lt': end, '$gte': start}, 'porta': 'A0'})

{u'_id': ObjectId('5435be9ce7b9916e02ed2cb5'),
 u'datahora': datetime.datetime(2014, 9, 24, 7, 51, 5),
 u'id_no': 1.0,
 u'lab': u'2',
 u'porta': u'A0',
 u'sensor': u'1',
 u'valor': u'917'}

https://stackoverflow.com/questions/26366417/how-to-make-a-query-date-in-mongodb-using-pymongo

 

How to make a query date in mongodb using pymongo?

I'm trying to perform a query date in mongodb, but the result is always empty. My query is as follows: //in the begin code def __init__(self): self.now = datetime.now() self.db = conexaoMo...

stackoverflow.com

 

* Aggregate를 이용하여 조건에 맞는 데이터를 추출해서 삭제하는 방법

db.grades.aggregate( [ 
                            { 
                                $match:{type:'homework'}
                            }, 
                            { $group: 
                                 { _id: {student_id:"$student_id",type:'$type'},                                   
                                   score: { $max: "$score" } 
                                 } 
                            } 
                            ]).forEach(function(doc){
db.grades.remove({'student_id':doc._id.student_id,'score':doc.score})

})

https://stackoverflow.com/questions/30615981/how-to-delete-the-documents-returned-by-group-in-mongodb/30616162

 

How to delete the documents returned by group in mongodb?

I am mongodb beginner and am working on a homework problem, the dataset looks like this { "_id" : { "$oid" : "50906d7fa3c412bb040eb577" }, "student_id" : 0, "type" : "exam", "score" : 54.653543636...

stackoverflow.com