Firavun faresi nasıl sıralanır?


Yanıtlar:


157

Mongoose'da, aşağıdaki yollardan biriyle bir sıralama yapılabilir:

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) { ... });

5
Bu, Francisco Presencia tarafından bağlanan cevabın neredeyse düz bir kopyası. Maalesef en yüksek oyu alan cevaplar modası geçmiş ve gereksiz yere uzun.
— iwein

2
Bugün itibariyle bu pek doğru değil. {sort: [['date', 1]]}işe yaramayacak, ama .sort([['date', -1]])işe yarayacak. Bu yanıta bakın: stackoverflow.com/a/15081087/404699
— steampowered

@steampowered teşekkürler, bir düzenleme yapacağım, yanlış anladıysam bana bildirebilir veya düzenleyebilirsiniz.
— iwein

135

Firavun faresi 2.3.0'da bu şekilde çalışmaya başladım :)

// 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
})

7
çitanýn 3'te sen kullanamazsınız Arrayartık saha seçimi için - bu olmak zorunda StringyaObject
— pkyeck

4
btw, tüm alanları istiyorsanız, nullo bölümü çekebilirsiniz (en az 3.8'de)
— MalcolmOcean

63

Mongoose 3.8.x itibariyle:

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

Nerede:

criteriaolabilir asc, desc, ascending, descending, 1, ya da-1


52

GÜNCELLEME:

Post.find().sort({'updatedAt': -1}).all((posts) => {
  // do something with the array of posts
});

Deneyin:

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

13
En son Firavun Faresi'nde (2.4.10) .sort("updatedAt", -1).
— Marcel Jackwerth

43
Daha da yeni Mongoose'da (3.5.6 öncesi, ama eminim ki tüm 3.x için geçerli) .sort({updatedAt: -1})ya da .sort('-updatedAt').
— Andreas Hultgren

2
Sonra kullanmalıdır exec(function (posts) {…yerineall
— Buzut

Bir var all() must be used after where() when called with these arguments... Gelincik 4.6.5 yılında
— Baraj Fa'yı

25

Firavun faresi v5.4.3

artan sıraya göre sırala

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) { ... });

azalan sıraya göre sırala

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) { ... });

Ayrıntılar için: https://mongoosejs.com/docs/api.html#query_Query-sort


23

Güncelleme

Bu insanları kafa karıştırıyorsa daha iyi bir yazı var; belgeleri bulma ve sorguların tek renkli el kitabında nasıl çalıştığını kontrol edin . Akıcı api'yi kullanmak istiyorsanız, find()yönteme geri çağrı sağlayarak bir sorgu nesnesi alabilirsiniz , aksi takdirde parametreleri aşağıda özetlediğim gibi belirtebilirsiniz.

orijinal

Bir modelnesne göz önüne alındığında , Model üzerindeki dokümanlar uyarınca şu şekilde çalışabilir 2.4.1:

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

search specBir nesneyi beklediğini, ancak geçebilir nullveya boş bir nesne.

İkinci parametre, bir dize dizisi olarak alan listesidir, bu nedenle ['field','field2']veya sağlarsınız null.

Üçüncü parametre, sonuç kümesini sıralama yeteneğini içeren bir nesne olarak seçeneklerdir. Sen kullanırsınız { sort: { field: direction } }nerede fielddize AlanAdı olan test(senin durumunda) ve directionbir sayıdır 1artan ve -1desceding edilir.

Son parametre ( callback), sorgu tarafından döndürülen belgelerin toplanmasını alan geri arama işlevidir.

Model.find()(Bu versiyonda en) uygulaması isteğe bağlı params işlemek için özellikler sürgülü tahsisini yapar (beni karıştı budur!):

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


projeksiyon için: boşlukla ayrılmış sütun adlarını içeren bir dize sağlamalıyız.
— maddy

11

Bu şekilde mongoose.js 2.0.4'te çalışmaya başladım

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

10

Mongoose 4'te sorgu oluşturucu arayüzü ile zincirleme.

// 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
})

Sorgular hakkında daha fazla bilgi için dokümanlara bakın .


4

yalnızca tek bir sütuna göre sıralamak istiyorsanız, mongoose'un (1.6.0) geçerli sürümü ile diziyi bırakmanız ve nesneyi doğrudan sort () işlevine geçirmeniz gerekir:

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

bunu düzeltmem için bana biraz zaman ayırdı :(


Teşekkürler. yayının bana yardımcı oldu. Ben de bununla yüzleştim.
— user644745

4
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)
    })
})

Çıktı

[ { _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 } ]

3

Ben sıralamak ve doldurmak nasıl başardı:

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


2

Diğerleri benim için çalıştı, ama bu işe yaradı:

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

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


1

4.x'ten itibaren sıralama yöntemleri değiştirildi. > 4.x kullanıyorsanız. Aşağıdakilerden herhangi birini kullanmayı deneyin.

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

0
Post.find().sort('updatedAt').exec((err, post) => {...});

1
Merhaba ve topluluğa hoş geldiniz. Cevabınız bir çözüm sunsa da, iyi bir cevap biraz açıklama gerektirir. Lütfen bazı referanslar ve uygun bir açıklama ekleyin.
— Panda
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.