programing tip

MongoDB에서 날짜별로 컬렉션을 정렬하는 방법은 무엇입니까?

itbloger 2020. 7. 30. 10:07
반응형

MongoDB에서 날짜별로 컬렉션을 정렬하는 방법은 무엇입니까?


Node.JS와 함께 MongoDB를 사용하고 있습니다. 날짜와 다른 행을 포함하는 컬렉션이 있습니다. 날짜는 JavaScript Date객체입니다.

이 컬렉션을 날짜별로 정렬하려면 어떻게합니까?


@JohnnyHK 답변을 약간 수정했습니다.

collection.find().sort({datefield: -1}, function(err, cursor){...});

많은 사용 사례에서 최신 업데이트 / 삽입과 같은 최신 레코드를 반환하려고합니다.


날짜별로 정렬 할 때는 특별한 것이 필요하지 않습니다. 컬렉션의 원하는 날짜 필드를 기준으로 정렬하십시오.

1.4.28 node.js 기본 드라이버 용으로 업데이트되었으며 datefield다음 방법 중 하나 사용하여 오름차순으로 정렬 할 수 있습니다 .

collection.find().sort({datefield: 1}).toArray(function(err, docs) {...});
collection.find().sort('datefield', 1).toArray(function(err, docs) {...});
collection.find().sort([['datefield', 1]]).toArray(function(err, docs) {...});
collection.find({}, {sort: {datefield: 1}}).toArray(function(err, docs) {...});
collection.find({}, {sort: [['datefield', 1]]}).toArray(function(err, docs) {...});

'asc'또는 'ascending'대신에 사용할 수도 있습니다 1.

정렬 내림차순, 사용하려면 'desc', 'descending'또는 -1의 장소 1.


db.getCollection('').find({}).sort({_id:-1}) 

삽입 날짜를 기준으로 컬렉션을 내림차순으로 정렬합니다.


Sushant Gupta의 답변은 다소 구식이며 더 이상 작동하지 않습니다.

다음 스 니펫은 이제 다음과 같아야합니다.

collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});


이것은 나를 위해 일했다 :

collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... });

Node.js, Express.js 및 Monk 사용


collection.find().sort('date':1).exec(function(err, doc) {});

이것은 나를 위해 일했다

참조 https://docs.mongodb.org/getting-started/node/query/


몽구스를 사용하면 다음과 같이 간단합니다.

collection.find().sort('-date').exec(function(err, collectionItems) {
  // here's your code
})

정렬 매개 변수가 작동하려면 추가 사각형 [] 브래킷이 필요합니다.

collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});

날짜 형식이 다음과 같은 경우 : 14/02/1989 ----> 문제가 발생할 수 있습니다

다음과 같이 ISOdate를 사용해야합니다.

var start_date = new Date(2012, 07, x, x, x); 

-----> 결과 ------> ISODate ( "2012-07-14T08 : 14 : 00.201Z")

이제 다음과 같은 쿼리를 사용하십시오.

 collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...}

그게 다야 :)


mongoose를 사용하면 'toArray'를 사용할 수 없었고 오류가 발생했습니다. TypeError: Collection.find(...).sort(...).toArray is not a function.toArray 함수는 Native MongoDB NodeJS 드라이버 ( reference ) 의 Cursor 클래스에 있습니다 .

또한 sort는 하나의 매개 변수 만 허용하므로 그 안에 함수를 전달할 수 없습니다.

이것은 Emil 에게 답변 한대로 나를 위해 일했습니다 .

collection.find().sort('-date').exec(function(error, result) {
  // Your code
})

참고 URL : https://stackoverflow.com/questions/13847766/how-to-sort-a-collection-by-date-in-mongodb

반응형