programing

두 날짜 사이의 객체 찾기 MongoDB

css3 2023. 3. 21. 22:25

두 날짜 사이의 객체 찾기 MongoDB

mongodb에 트윗을 저장하면서 놀고 있는데, 각각의 오브젝트는 다음과 같습니다.

{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"contributors" : null,
"text" : "Hello world",
"user" : {
    "following" : null,
    "followers_count" : 5,
    "utc_offset" : null,
    "location" : "",
    "profile_text_color" : "000000",
    "friends_count" : 11,
    "profile_link_color" : "0000ff",
    "verified" : false,
    "protected" : false,
    "url" : null,
    "contributors_enabled" : false,
    "created_at" : "Sun May 30 18:47:06 +0000 2010",
    "geo_enabled" : false,
    "profile_sidebar_border_color" : "87bc44",
    "statuses_count" : 13,
    "favourites_count" : 0,
    "description" : "",
    "notifications" : null,
    "profile_background_tile" : false,
    "lang" : "en",
    "id" : 149978111,
    "time_zone" : null,
    "profile_sidebar_fill_color" : "e0ff92"
},
"geo" : null,
"coordinates" : null,
"in_reply_to_user_id" : 149183152,
"place" : null,
"created_at" : "Sun May 30 20:07:35 +0000 2010",
"source" : "web",
"in_reply_to_status_id" : {
    "floatApprox" : 15061797850
},
"truncated" : false,
"favorited" : false,
"id" : {
    "floatApprox" : 15061838001
}

created_at를 체크하고 18:47에서 19:00 사이의 모든 개체를 찾는 쿼리를 작성하려면 어떻게 해야 합니까?날짜가 특정 형식으로 저장되도록 문서를 업데이트해야 합니까?

날짜 범위 쿼리(특정 월 또는 일)에서 MongoDB 요리책이 문제에 대한 설명은 매우 훌륭하지만, 아래는 제가 직접 시도해 본 결과 효과가 있는 것 같습니다.

items.save({
    name: "example",
    created_at: ISODate("2010-04-30T00:00:00.000Z")
})
items.find({
    created_at: {
        $gte: ISODate("2010-04-29T00:00:00.000Z"),
        $lt: ISODate("2010-05-01T00:00:00.000Z")
    }
})
=> { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }

제 실험에 따르면, MongoDB가 지원하는 형식으로 날짜를 일련화할 필요가 있습니다.왜냐하면 다음은 원치 않는 검색 결과를 제공했기 때문입니다.

items.save({
    name: "example",
    created_at: "Sun May 30 18.49:00 +0000 2010"
})
items.find({
    created_at: {
        $gte:"Mon May 30 18:47:00 +0000 2015",
        $lt: "Sun May 30 20:40:36 +0000 2010"
    }
})
=> { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }

두 번째 예에서는 기대한 결과는 없었지만 얻은 결과는 하나뿐이었습니다.이는 기본적인 문자열 비교가 이루어지기 때문입니다.

명확히 하다.중요한 것은 다음과 같습니다.

  • 예, Javascript Date 개체를 전달해야 합니다.
  • 네, 이소데이트 친화적이어야 합니다.
  • 네, 지금까지의 경험으로 볼 때 ISO로 날짜를 조작할 필요가 있습니다.
  • 네, 데이트 관련 작업은 항상 지루한 과정이며 mongo도 예외는 아닙니다.

여기에서는 Mongo(여기서는 mongoose 모듈을 사용하고 있으며 myDate 파라미터로 지정된 날짜보다 이전 날짜 속성을 가진 행에 대한 결과를 원합니다)를 올바르게 처리하기 위해 약간의 날짜 조작을 수행합니다.

var inputDate = new Date(myDate.toISOString());
MyModel.find({
    'date': { $lte: inputDate }
})

및 Python »pymongo

과 Python의 두 pymongo되어 있다posts(자습서 기준):

from_date = datetime.datetime(2010, 12, 31, 12, 30, 30, 125000)
to_date = datetime.datetime(2011, 12, 31, 12, 30, 30, 125000)

for post in posts.find({"date": {"$gte": from_date, "$lt": to_date}}):
    print(post)

서 ★★★★★{"$gte": from_date, "$lt": to_date}합니다.datetime.datetimetypes.timeout.

db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();

collection with want to execute 。

MongoDB는 실제로 http://bsonspec.org/ #/specification에 규정된 날짜의 밀리를 int(64)로 저장합니다.

단, 클라이언트드라이버가 자신의 로컬 시간대로 날짜 객체를 인스턴스화하므로 날짜를 검색할 때 상당히 혼란스러울 수 있습니다.mongo 콘솔의 JavaScript 드라이버는 반드시 이 작업을 수행합니다.

그러니, 만약 당신이 타임존을 신경 쓴다면, 그것을 돌려받을 때 그것이 무엇인지 확실히 알아야 한다.날짜 객체가 있는 시간대에 관계없이 동일한 int(64)에 해당하므로 쿼리에 크게 문제가 되지 않습니다(기대).하지만 저는 반드시 실제 날짜 오브젝트(문자열이 아닌)로 쿼리를 작성하여 드라이버에게 작업을 맡길 것입니다.

이 코드를 사용하여 두 날짜 사이의 레코드를 찾습니다.$gte그리고.$lt:

db.CollectionName.find({"whenCreated": {
    '$gte': ISODate("2018-03-06T13:10:40.294Z"),
    '$lt': ISODate("2018-05-06T13:10:40.294Z")
}});

Moment.js비교 쿼리 연산자와 함께 사용

  var today = moment().startOf('day');
  // "2018-12-05T00:00:00.00
  var tomorrow = moment(today).endOf('day');
  // ("2018-12-05T23:59:59.999

  Example.find(
  {
    // find in today
    created: { '$gte': today, '$lte': tomorrow }
    // Or greater than 5 days
    // created: { $lt: moment().add(-5, 'days') },
  }), function (err, docs) { ... });
db.collection.find({$and:
  [
    {date_time:{$gt:ISODate("2020-06-01T00:00:00.000Z")}},
     {date_time:{$lt:ISODate("2020-06-30T00:00:00.000Z")}}
   ]
 })

##In case you are making the query directly from your application ##

db.collection.find({$and:
   [
     {date_time:{$gt:"2020-06-01T00:00:00.000Z"}},
     {date_time:{$lt:"2020-06-30T00:00:00.000Z"}}
  ]

 })

이것 또한 확인하실 수 있습니다.이 메서드를 사용하는 경우 해석 함수를 사용하여 Mongo 데이터베이스에서 값을 가져옵니다.

db.getCollection('user').find({
    createdOn: {
        $gt: ISODate("2020-01-01T00:00:00.000Z"),
        $lt: ISODate("2020-03-01T00:00:00.000Z")
    }
})

created_at 날짜를 ISO 날짜 형식으로 저장한 후 $gte 및 $lte를 사용합니다.

db.connection.find({
    created_at: {
        $gte: ISODate("2010-05-30T18:47:00.000Z"),
        $lte: ISODate("2010-05-30T19:00:00.000Z")
    }
})

$gte $190을 사용하여 mongodb의 날짜 데이터를 찾습니다.

var tomorrowDate = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
db.collection.find({"plannedDeliveryDate":{ $gte: new Date(tomorrowDate +"T00:00:00.000Z"),$lte: new Date(tomorrowDate + "T23:59:59.999Z")}})

문자열을 YYYYMMDDHHMMSS 형식의 정수로 변환하는 것은 어떨까요? 그러면 시간이 늘어날 때마다 더 큰 정수가 생성되므로 ISO 시간으로 변환하는 대신 정수를 필터링할 수 있습니다.

mongoose.model('ModelName').aggregate([
    {
        $match: {
            userId: mongoose.Types.ObjectId(userId)
        }
    },
    {
        $project: {
            dataList: {
              $filter: {
                 input: "$dataList",
                 as: "item",
                 cond: { 
                    $and: [
                        {
                            $gte: [ "$$item.dateTime", new Date(`2017-01-01T00:00:00.000Z`) ]
                        },
                        {
                            $lte: [ "$$item.dateTime", new Date(`2019-12-01T00:00:00.000Z`) ]
                        },
                    ]
                 }
              }
           }
        }
     }
])

Make(구 Integomat)와 MongoDB를 사용하는 사용자: 두 날짜 사이에 모든 레코드를 조회하는 올바른 방법을 찾느라 고생했습니다.결국, 여기의 솔루션 중 몇 가지에 제시된 대로 삭제만 하면 되었습니다.

따라서 전체 코드는 다음과 같습니다.

"created": {
    "$gte": "2016-01-01T00:00:00.000Z",
    "$lt": "2017-01-01T00:00:00.000Z"
}

기사는 나의 목표를 달성하는 데 도움이 되었다.


갱신하다

Make(구 Integomat)에서 위의 코드를 얻는 또 다른 방법은 parseDate 함수를 사용하는 것입니다.따라서 아래 코드는 위와 같은 결과를 반환합니다.

"created": {
    "$gte": "{{parseDate("2016-01-01"; "YYYY-MM-DD")}}",
    "$lt": "{{parseDate("2017-01-01"; "YYYY-MM-DD")}}"
}

⚠ be 반드시 포장해 주세요{{parseDate("2017-01-01"; "YYYY-MM-DD")}}따옴표 사이에 있습니다.

날짜를 GMT 표준시로 변환하여 Mongo에 넣습니다.그래야 시간대 문제가 없어프레젠테이션용으로 데이터를 꺼낼 때는 twitter/timezone 필드에서 계산만 하면 됩니다.

Scala: joda Date Time 및 BSON 구문(reactive mongo):

val queryDateRangeForOneField = (start: DateTime, end: DateTime) =>
    BSONDocument(
      "created_at" -> BSONDocument(
        "$gte" -> BSONDateTime(start.millisOfDay().withMinimumValue().getMillis), 
        "$lte" -> BSONDateTime(end.millisOfDay().withMaximumValue().getMillis)),
     )

어디에millisOfDay().withMinimumValue()'102-09-08'의 경우T06:42:51.697Z는 "2021-09-08"이 됩니다.T00:00:00.000Z" 및 장소millisOfDay(). withMaximumValue()'102-09-08'의 경우T06:42:51.697Z"는 "2021-09-08T23:59:99.999Z"가 됩니다.

요구 사항에 따라 이 모델에서 시도했습니다.나중에 오브젝트가 생성될 때마다 날짜를 저장해야 합니다.내 html 파일에 있는 두 날짜 사이의 모든 레코드(예:)를 가져오고 싶습니다.다음 형식을 사용하고 있었습니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>

    <script>
//jquery
    $(document).ready(function(){  
    $("#select_date").click(function() { 
    $.ajax({
    type: "post",
    url: "xxx", 
    datatype: "html",
    data: $("#period").serialize(),  
    success: function(data){
    alert(data);
    } ,//success

    }); //event triggered

    });//ajax
    });//jquery  
    </script>

    <title></title>
</head>

<body>
    <form id="period" name='period'>
        from <input id="selecteddate" name="selecteddate1" type="text"> to 
        <input id="select_date" type="button" value="selected">
    </form>
</body>
</html>

내 py(py) 파일에서 나는 다음과 같은 방법으로 그것을 "iso formate"로 변환했다.

date_str1   = request.POST["SelectedDate1"] 
SelectedDate1   = datetime.datetime.strptime(date_str1, '%m/%d/%Y').isoformat()

dbmongo 컬렉션에 "SelectedDate" 필드로 저장했습니다.

쿼리 후 사용한 날짜에서 최대 2일 사이에 데이터 또는 문서를 검색합니다.

db.collection.find( "SelectedDate": {'$gte': SelectedDate1,'$lt': SelectedDate2}})

언급URL : https://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb