MongoDB: adding sort () to query the result set for $ and query

I came across a very strange behavior with MongoDB. For my test case, I have a MongoDB collection with 9 documents. All documents have the same structure, including expired_at: Dateand fields location: [lng, lat].

Now I need to find all the documents that have not yet expired and are in the bounding box; I show the relevant documents on the map. for this I asked the following queries:

var qExpiry = {"expired_at": { $gt : new Date() } };
var qLocation = { "location" : { $geoWithin : { $box : [ [ 123.8766, 8.3269 ] , [ 122.8122, 8.24974 ] ] } } };
var qFull = { $and: [ qExpiry, qLocation ] };

Since the expiration date is in the past, and when I set the bounding box large enough, the following queries give me all 9 documents, as expected:

db.docs.find(qExpiry);
db.docs.find(qLocation);
db.docs.find(qFull);
db.docs.find(qExpiry).sort({"created_at" : -1});
db.docs.find(qLocation).sort({"created_at" : -1});

Now here is the deal: The following query returns 0 documents:

db.docs.find(qFull).sort({"created_at" : -1});

AND ( , , , ). . ?

( : , qFull . , qLocation . qLocation, . qExpiry )

+4
2

, , $match $sort :

db.docs.aggregate([
    { "$match": qFull },
    { "$sort": { "created_at": -1 } }
]);

$and, , ,

db.docs.aggregate([
    { 
        "$match": {
            "expired_at": { "$gt" : new Date() },
            "location" : { 
                "$geoWithin" : { 
                    "$box" : [ 
                        [ 123.8766, 8.3269 ], 
                        [ 122.8122, 8.24974 ] 
                    ] 
                } 
            }
        } 
    },
    { "$sort": { "created_at": -1 } }
]);

, find()

+2

chridam, MongoDB, . :

db.docs.aggregate(
    [ 
      { $match : { $and : [qExpiry, qLocation]} },
      { $sort: {"created_at": -1} }.
      { $limit: 50 }.
    ]
);

, - , , . sort() 0 . , , .sort({}) , . .sort({'_id': 1}).

+1

Source: https://habr.com/ru/post/1670048/


All Articles