IT박스

날짜별로 MongoDB ObjectId를 쿼리 할 수 ​​있습니까?

itboxs 2020. 6. 28. 19:24
반응형

날짜별로 MongoDB ObjectId를 쿼리 할 수 ​​있습니까?


ObjectId에 작성된 날짜가 포함되어 있음을 알고 있습니다. ObjectId 의이 측면을 쿼리하는 방법이 있습니까?


타임 스탬프를 ObjectId에 넣는 것은 ObjectId에 포함 된 날짜를 기반으로하는 쿼리를 매우 자세하게 다룹니다.

JavaScript 코드에서 간단히 :

// This function returns an ObjectId embedded with a given datetime
// Accepts both Date object and string input

function objectIdWithTimestamp(timestamp) {
    // Convert string date to Date object (otherwise assume timestamp is a date)
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    // Convert date object to hex seconds since Unix epoch
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    // Create an ObjectId with that hex timestamp
    var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
}


// Find all documents created after midnight on May 25th, 1980
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });

에서 다음 pymongo과 같이 할 수 있습니다.

import datetime
from bson.objectid import ObjectId
mins = 15
gen_time = datetime.datetime.today() - datetime.timedelta(mins=mins) 
dummy_id = ObjectId.from_datetime(gen_time)
result = list(db.coll.find({"_id": {"$gte": dummy_id}}))

Node.js의 mongodb 드라이버가 제공하는 내장 함수를 사용하면 타임 스탬프별로 쿼리 할 수 ​​있습니다.

var timestamp = Date.now();
var objectId = ObjectID.createFromTime(timestamp / 1000);

또는 현재 시간 전에 레코드를 검색하려면 다음을 수행하십시오.

var objectId = new ObjectID(); // or ObjectId in the mongo shell

출처 : http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html


ObjectId의 처음 4 바이트 는 timestamp를 나타내 므로 컬렉션을 시간순으로 쿼리하려면 간단히 id로 정렬하십시오.

# oldest first; use pymongo.DESCENDING for most recent first
items = db.your_collection.find().sort("_id", pymongo.ASCENDING)

문서를 얻은 후 다음 과 같이 ObjectId의 생성 시간을 얻을 수 있습니다 .

id = some_object_id
generation_time = id.generation_time

명령을 찾는 방법 (이 날짜 [2015-1-12]부터이 날짜 [2015-1-15]) :

db.collection.find ({_ id : {$ gt : ObjectId (Math.floor ((new Date ( '2015/1/12')) / 1000) .toString (16) + "0000000000000000"), $ lt : ObjectId (Math.floor ((새 날짜 ( '2015/1/15')) / 1000) .toString (16) + "0000000000000000")}}). pretty ()

명령을 세십시오 (이 날짜 [2015-1-12]부터이 날짜 [2015-1-15]) :

db.collection.count ({_ id : {$ gt : ObjectId (Math.floor ((new Date ( '2015/1/12')) / 1000) .toString (16) + "0000000000000000"), $ lt : ObjectId (Math.floor ((새 날짜 ( '2015/1/15')) / 1000) .toString (16) + "0000000000000000")}))

명령을 제거하십시오 (이 날짜 [2015-1-12]부터이 날짜 [2015-1-15]까지) :

db.collection.remove ({_ id : {$ gt : ObjectId (Math.floor ((new Date ( '2015/1/12')) / 1000) .toString (16) + "0000000000000000"), $ lt : ObjectId (Math.floor ((새 날짜 ( '2015/1/15')) / 1000) .toString (16) + "0000000000000000")}))


$convert4.0 버전부터 ObjectId에서 날짜를 추출하는 함수를 사용할 수 있습니다 .

같은 것

$convert: { input: "$_id", to: "date" } 

날짜의 시작 시간과 종료 시간을 비교하여 날짜를 쿼리 할 수 ​​있습니다.

db.collectionname.find({
  "$expr":{
    "$and":[
      {"$gte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2018-07-03T00:00:00.000Z")]},
      {"$lte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2018-07-03T11:59:59.999Z")]}
    ]
  }
})

또는

속기 $toDate사용 하여 동일한 결과를 얻을 수 있습니다 .

db.collectionname.find({
  "$expr":{
    "$and":[
      {"$gte":[{"$toDate":"$_id"}, ISODate("2018-07-03T00:00:00.000Z")]},
      {"$lte":[{"$toDate":"$_id"},ISODate("2018-07-03T11:59:59.999Z")]}
    ]
  }
})

몽고 컬렉션에서 지난 60 일 된 문서를 얻으려면 셸에서 아래 쿼리를 사용했습니다.

db.collection.find({_id: {$lt:new ObjectId( Math.floor(new Date(new Date()-1000*60*60*24*60).getTime()/1000).toString(16) + "0000000000000000" )}})

범위 쿼리를 만들고 싶다면 이 게시물 에서처럼 할 수 있습니다 . 예를 들어 특정 날짜 (예 : 2015 년 4 월 4 일)에 대한 쿼리 :

> var objIdMin = ObjectId(Math.floor((new Date('2015/4/4'))/1000).toString(16) + "0000000000000000")
> var objIdMax = ObjectId(Math.floor((new Date('2015/4/5'))/1000).toString(16) + "0000000000000000")
> db.collection.find({_id:{$gt: objIdMin, $lt: objIdMax}}).pretty()

설명서에서 :

o = new ObjectId()
date = o.getTimestamp()

이렇게하면 날짜가 ISODate입니다.

Look at http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhavingaseparatetimestampfield. for more information


Using MongoObjectID you should also find results as given below

db.mycollection.find({ _id: { $gt: ObjectId("5217a543dd99a6d9e0f74702").getTimestamp().getTime()}});

참고URL : https://stackoverflow.com/questions/8749971/can-i-query-mongodb-objectid-by-date

반응형