복붙노트

[MONGODB] 어떻게 몽구스에 정렬하려면?

MONGODB

어떻게 몽구스에 정렬하려면?

나는 정렬 수정에 대한 문서를 찾을 수 없습니다. 유일한 통찰력은 단위 테스트에 있습니다 : spec.lib.query.js # L12

writer.limit(5).sort(['test', 1]).group('name')

그러나 그것은 나를 위해 작동하지 않습니다

Post.find().sort(['updatedAt', 1]);

해결법

  1. ==============================

    1.이것은 내가 몽구스 2.3.0에서 작업에 일종의 도착하는 방법입니다 :)

    이것은 내가 몽구스 2.3.0에서 작업에 일종의 도착하는 방법입니다 :)

    // Find First 10 News Items
    News.find({
        deal_id:deal._id // Search Filters
    },
    ['type','date_added'], // Columns to Return
    {
        skip:0, // Starting Row
        limit:10, // Ending Row
        sort:{
            date_added: -1 //Sort by Date Added DESC
        }
    },
    function(err,allNews){
        socket.emit('news-load', allNews); // Do something with the array of 10 objects
    })
    
  2. ==============================

    2.몽구스에서 일종의는 다음과 같은 방법으로 수행 할 수 있습니다 :

    몽구스에서 일종의는 다음과 같은 방법으로 수행 할 수 있습니다 :

    Post.find({}).sort('test').exec(function(err, docs) { ... });
    Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
    Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
    Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
    
  3. ==============================

    3.몽구스의 3.8.x의로 :

    몽구스의 3.8.x의로 :

    model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
    

    어디에:

    기준 오름차순, 내림차순, 오름차순, 내림차순으로, 1, 또는 수 -1

  4. ==============================

    4.시험:

    시험:

    Post.find().sort([['updatedAt', 'descending']]).all(function (posts) {
      // do something with the array of posts
    });
    
  5. ==============================

    5.최신 정보

    최신 정보

    이 혼란 사람들 인 경우가 더 잘 쓰기가있다; 문서를 찾아 확인하는 방법 쿼리는 몽구스 설명서에서 작동합니다. 당신은 유창하게 API를 사용하려는 경우 당신은 내가 아래 개요로, 그렇지 않으면 당신은 매개 변수를 지정할 수 있습니다, 찾기 () 메소드에 콜백을 제공하지 않음으로써 질의 객체를 얻을 수 있습니다.

    기발한

    모델 객체 감안할 때, 모델에 문서 당이는 2.4.1 작동 할 수있는 방법입니다 :

    Post.find({search-spec}, [return field array], {options}, callback)
    

    검색 사양은 객체를 기대하고 있지만, null 또는 빈 개체를 전달할 수 있습니다.

    만약 [ '필드', 'FIELD2'] null를 제공 할 수 있도록 제 PARAM는 문자열 배열로 필드리스트이다.

    세번째 PARAM 결과 집합을 정렬하는 기능을 포함하는 오브젝트로서 선택한다. 당신이 사용하는 것이 {종류 : {필드 : 방향}} 필드 (귀하의 경우) 문자열 필드 이름 시험과 방향 (1)가 상승되고 -1 desceding되는 번호입니다.

    최종 PARAM (콜백) 쿼리에 의해 반환 된 문서의 컬렉션을 수신 콜백 함수이다.

    (이 버전에서) Model.find () 구현은 선택 PARAMS을 처리 할 수있는 속성의 슬라이딩 할당하지 (저를 혼동 무엇 인을!)

    Model.find = function find (conditions, fields, options, callback) {
      if ('function' == typeof conditions) {
        callback = conditions;
        conditions = {};
        fields = null;
        options = null;
      } else if ('function' == typeof fields) {
        callback = fields;
        fields = null;
        options = null;
      } else if ('function' == typeof options) {
        callback = options;
        options = null;
      }
    
      var query = new Query(conditions, options).select(fields).bind(this, 'find');
    
      if ('undefined' === typeof callback)
        return query;
    
      this._applyNamedScope(query);
      return query.find(callback);
    };
    

    HTH

  6. ==============================

    6.몽구스 v5.4.3

    몽구스 v5.4.3

    오름차순으로 정렬

    Post.find({}).sort('field').exec(function(err, docs) { ... });
    Post.find({}).sort({ field: 'asc' }).exec(function(err, docs) { ... });
    Post.find({}).sort({ field: 'ascending' }).exec(function(err, docs) { ... });
    Post.find({}).sort({ field: 1 }).exec(function(err, docs) { ... });
    
    Post.find({}, null, {sort: { field : 'asc' }}), function(err, docs) { ... });
    Post.find({}, null, {sort: { field : 'ascending' }}), function(err, docs) { ... });
    Post.find({}, null, {sort: { field : 1 }}), function(err, docs) { ... });
    

    내림차순으로 정렬

    Post.find({}).sort('-field').exec(function(err, docs) { ... });
    Post.find({}).sort({ field: 'desc' }).exec(function(err, docs) { ... });
    Post.find({}).sort({ field: 'descending' }).exec(function(err, docs) { ... });
    Post.find({}).sort({ field: -1 }).exec(function(err, docs) { ... });
    
    
    Post.find({}, null, {sort: { field : 'desc' }}), function(err, docs) { ... });
    Post.find({}, null, {sort: { field : 'descending' }}), function(err, docs) { ... });
    Post.find({}, null, {sort: { field : -1 }}), function(err, docs) { ... });
    

    자세한 내용은 : https://mongoosejs.com/docs/api.html#query_Query-sort

  7. ==============================

    7.이것은 내가 mongoose.js 2.0.4에서 업무 종류 가지고 어떻게

    이것은 내가 mongoose.js 2.0.4에서 업무 종류 가지고 어떻게

    var query = EmailModel.find({domain:"gmail.com"});
    query.sort('priority', 1);
    query.exec(function(error, docs){
      //...
    });
    
  8. ==============================

    8.몽구스 4 쿼리 빌더 인터페이스 체인.

    몽구스 4 쿼리 빌더 인터페이스 체인.

    // Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
    var query = Person.
        find({ occupation: /host/ }).
        where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
        where('age').gt(17).lt(66).
        where('likes').in(['vaporizing', 'talking']).
        limit(10).
        sort('-occupation'). // sort by occupation in decreasing order
        select('name occupation'); // selecting the `name` and `occupation` fields
    
    
    // Excute the query at a later time.
    query.exec(function (err, person) {
        if (err) return handleError(err);
        console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
    })
    

    쿼리에 대한 자세한의 문서를 참조하십시오.

  9. ==============================

    9.당신은 하나의 열을 기준으로 정렬 할 경우 몽구스 (1.6.0)의 최신 버전으로, 당신은 배열을 드롭) (정렬에 직접 기능을 개체를 전달할 수 있습니다 :

    당신은 하나의 열을 기준으로 정렬 할 경우 몽구스 (1.6.0)의 최신 버전으로, 당신은 배열을 드롭) (정렬에 직접 기능을 개체를 전달할 수 있습니다 :

    Content.find().sort('created', 'descending').execFind( ... );
    

    이 권리를 얻기 위해, 좀 시간이 걸렸습니다 :(

  10. ==============================

    10.이것은 내가 종류 및 채우는 관리하는 방법입니다 :

    이것은 내가 종류 및 채우는 관리하는 방법입니다 :

    Model.find()
    .sort('date', -1)
    .populate('authors')
    .exec(function(err, docs) {
        // code here
    })
    
  11. ==============================

    11.다른 사람은 나를 위해 일하지만, 이것은했다 :

    다른 사람은 나를 위해 일하지만, 이것은했다 :

      Tag.find().sort('name', 1).run(onComplete);
    
  12. ==============================

    12.

    Post.find().sort({updatedAt: 1});
    
  13. ==============================

    13.

    Post.find().sort({updatedAt:1}).exec(function (err, posts){
    ...
    });
    
  14. ==============================

    14.이것은 내가 그것을 잘 작동 한 것입니다.

    이것은 내가 그것을 잘 작동 한 것입니다.

    User.find({name:'Thava'}, null, {sort: { name : 1 }})
    
  15. ==============================

    15.

    app.get('/getting',function(req,res){
        Blog.find({}).limit(4).skip(2).sort({age:-1}).then((resu)=>{
            res.send(resu);
            console.log(resu)
            // console.log(result)
        })
    })
    

    산출

    [ { _id: 5c2eec3b8d6e5c20ed2f040e, name: 'e', age: 5, __v: 0 },
      { _id: 5c2eec0c8d6e5c20ed2f040d, name: 'd', age: 4, __v: 0 },
      { _id: 5c2eec048d6e5c20ed2f040c, name: 'c', age: 3, __v: 0 },
      { _id: 5c2eebf48d6e5c20ed2f040b, name: 'b', age: 2, __v: 0 } ]
    
  16. from https://stackoverflow.com/questions/4299991/how-to-sort-in-mongoose by cc-by-sa and MIT license