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
'programing tip' 카테고리의 다른 글
JSON.parse 예기치 않은 문자 오류 (0) | 2020.07.30 |
---|---|
예외 또는 오류 코드에 대한 규칙 (0) | 2020.07.30 |
psql을 사용할 때 postgres에서 스키마를 선택하는 방법은 무엇입니까? (0) | 2020.07.30 |
BoxLayout을 공유 할 수 없습니다 오류 (0) | 2020.07.30 |
긴 텍스트 문자열에서 모든 줄 바꿈 제거 (0) | 2020.07.30 |