programing

MongoDB에서 속성을 텍스트에서 날짜 유형으로 변환하려면 어떻게 해야 합니까?

elecom 2023. 5. 18. 20:45
반응형

MongoDB에서 속성을 텍스트에서 날짜 유형으로 변환하려면 어떻게 해야 합니까?

MongoDB에는 다음과 같은 필드가 있는 문서가 있습니다."ClockInTime"CSV에서 문자열로 가져온 데이터입니다.

무엇이 적절한 것db.ClockTime.update()문장이 이러한 텍스트 기반 값을 날짜 데이터 유형으로 변환하는 것처럼 보입니까?

이 코드는 다음을 수행해야 합니다.

> var cursor = db.ClockTime.find()
> while (cursor.hasNext()) {
... var doc = cursor.next();
... db.ClockTime.update({_id : doc._id}, {$set : {ClockInTime : new Date(doc.ClockInTime)}})
... }

저도 제프 프리츠와 똑같은 상황입니다.

저의 경우 다음과 같은 더 간단한 솔루션으로 성공했습니다.

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })

이것은 파이몬고를 사용하는 파이썬의 일반 샘플 코드입니다.

from pymongo import MongoClient
from datetime import datetime

def fixTime(host, port, database, collection, attr, date_format):
    #host is where the mongodb is hosted eg: "localhost"
    #port is the mongodb port eg: 27017
    #database is the name of database eg : "test"
    #collection is the name of collection eg : "test_collection"
    #attr is the column name which needs to be modified
    #date_format is the format of the string eg : "%Y-%m-%d %H:%M:%S.%f"
    #http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
    client = MongoClient(host, port)
    db = client[database]
    col = db[collection]
    for obj in col.find():
        if obj[attr]:
            if type(obj[attr]) is not datetime:
                time = datetime.strptime(obj[attr],date_format)
                col.update({'_id':obj['_id']},{'$set':{attr : time}})

자세한 내용은 http://salilpa.com/home/content/how-convert-property-mongodb-text-date-type-using-pymongo .

시작하는Mongo 4.x:

  • db.collection.update() 집계 파이프라인을 수락할 수 있으며, 최종적으로 현재 값을 기반으로 필드를 업데이트할 수 있습니다.Mongo 4.2+).
  • 새 집계 연산자가 있습니다(Mongo 4.0).

다음과 같은 경우:

// { a: "2018-03-03" }
db.collection.updateMany(
  {},
  [{ $set: { a: { $toDate: "$a" } } }]
)
// { a: ISODate("2018-03-03T00:00:00Z") }
  • 첫 번째 파트{}업데이트할 문서(이 경우 모든 문서)를 필터링하는 일치 쿼리입니다.

  • 제2부[{ $set: { a: { $toDate: "$a" } } }]업데이트 집계 파이프라인입니다(집계 파이프라인 사용을 나타내는 대괄호 참조).$set 이 경우 필드 값을 대체하는 새 집계 연산자입니다.대체된 값은 필드 자체가 일치하는 값입니다.ISODate물건.방법에 주목a자체 값을 기준으로 직접 수정됩니다($a).

필드가 이미 변환되었는지 확인해야 할 경우 다음 조건을 사용할 수 있습니다.

/usr/bin/mongo mydb --eval 'db.mycollection.find().forEach(function(doc){
    if (doc.date instanceof Date !== true) {
        doc.date = new ISODate(doc.date);
        db.mycollection.save(doc);
    }
});'

그렇지 않으면 명령줄이 중단될 수 있습니다.

언급URL : https://stackoverflow.com/questions/2900674/how-do-i-convert-a-property-in-mongodb-from-text-to-date-type

반응형