MongoDB pagination with location criteria - mongodb

I want get data sorted by field. For example
db.Users.find().limit(200).sort({'rating': -1}).skip(0)
It's work, I get sorted data. And can use pagination.
But, If add criteria .find({'location':{$near : [12,32], $maxDistance: 10}}) sorting doesn't work correctly.
Full the query:
db.Users.find({'location':{$near : [12,32], $maxDistance: 10}}).limit(200).sort({'rating': -1}).skip(0)
For example
Whithout criteria location:
offset 0
rating 100
rating 99
rating 98
rating 97
rating 96
offset 5
rating 95
rating 94
rating 93
rating 92
rating 91
offset 10
rating 90
rating 89
rating 88
rating 87
rating 86
With criteria location
offset 0
rating 100
rating 99
rating 98
rating 97
rating 96
offset 5
rating 90
rating 89
rating 88
rating 87
rating 86
offset 10
rating 95
rating 94
rating 93
rating 92
rating 91
What could be the problem? Can I use pagination with location criteria in MongoDB?

The aggregation framework has a way to do this using the $geoNear pipeline stage. Basically it will "project" a "distance" field which you can then use in a combination sort:
db.collection.aggregate([
{ "$geoNear": {
"near": [12,32],
"distanceField": "distance",
"maxDistance": 10
}},
{ "$sort": { "distance": 1, "rating" -1 } }
{ "$skip": 0 },
{ "$limit": 25 }
])
Should be fine, but "skip" and "limit" are not really efficient over large skips. If you can get away without needing "page numbering" and just want to go forwards, then try a different technique.
The basic principle is to keep track of the last distance value found for the page and also the _id values of the documents from that page or a few previous, which can then be filtered out using the $nin operator:
db.collection.aggregate([
{ "$geoNear": {
"near": [12,32],
"distanceField": "distance",
"maxDistance": 10,
"minDistance": lastSeenDistanceValue,
"query": {
"_id": { "$nin": seenIds },
"rating": { "$lte": lastSeenRatingValue }
},
"num": 25
}},
{ "$sort": { "distance": 1, "rating": -1 }
])
Essentially that is going to be a lot better, but it won't help you with jumps to "page" 25 for example. Not without a lot more effort in working that out.

Related

Get number of daily records, per month

I am trying to get some data visualization for an application I am making and I am currently having an issue.
The current query I am using to get the documents grouped by month is the following:
# Generating our pipeline
pipeline = [
{"$match": query_match
},
{"$group": {
'_id': {
'$dateTrunc': {
'date': "$date", 'unit': "month"
}
},
"total": {
"$sum": 1
}
}
},
{'$sort': {
'_id': 1
}
}
]
This however, will return me the sum of documents for each month.
I want to take this a step further and calculate the average number of documents per day. but ONLY for the days which I have collections for.
As an example, the above query currently returns something like this:
Index _id total_documents
0 2022-07-01 10425
1 2022-08-01 27981
2 2022-09-01 24872
3 2022-10-01 1633
What I want is, for 2022-7 for example, I have documents submitted for 20 of the 31 days that the month has, so I want to return 10452 / 20, instead of 10452 / 31 which would technically be the daily average for that month.
Is there a way to do this in a single aggregation or would I have to use an additional query to determine how many days I have documents for first?
Thanks

Mongodb relative frequency in grouping aggregation

I have data that looks like this
{"customer_id":1, "amount": 100, "item": "a"}
{"customer_id":1, "amount": 20, "item": "b"}
{"customer_id":2, "amount": 25, "item": "a"}
{"customer_id":3, "amount": 10, "item": "a"}
{"customer_id":4, "amount": 10, "item": "b"}
Using R I can get an overview of relative frequencies very easily by doing this
data %>%
group_by(customer_id,item) %>%
summarise(total=sum(amount)) %>%
mutate(per_customer_spend=total/sum(total))
Which returns;
customer_id item total per_customer_spend
<dbl> <chr> <dbl> <dbl>
1 1 a 100 0.833
2 1 b 20 0.167
3 2 a 25 1
4 3 a 10 1
5 4 b 10 1
I can't figure out how to do this in Mongo efficiently, the best solution I have so far involves multiple groups and pushing and unwinding.
If you don't want to change the data structure there's no way around grouping all the data as we need to determine the total amount spent of each user, though this would require just a single $group stage and a single $uwind stage, it would look somethine like this:
db.collection.aggregate([
{
$group: {
_id: "$customer_id",
total: {$sum: "$amount"},
rootHolder: {$push: "$$ROOT"}
}
},
{
$unwind: "$rootHolder"
},
{
$project: {
newRoot: {
$mergeObjects: [
"$rootHolder",
{total: "$total"}
]
}
}
},
{
$replaceRoot: {
newRoot: "$newRoot"
}
},
{
$project: {
customer_id: 1,
item: 1,
total: "$amount",
per_customer_spend: {$divide: ["$amount", "$total"]}
}
}
])
With that said, especially when scale increases this pipeline becomes very expensive, Now depending on how big the scale is and the amount of unique pairs of costumer_id x item i would advice the following:
considering Mongo doesn't like data duplication and assuming a user does not "buy" new items too often it might be worth to actually save it as a field in the current collection. (which requires updating all the users items on purchase), I know this sounds "weird" and costly but again depending on frequency of purchases it might actually be worth it.
Assuming you decide not to do the above I would instead create a new collection with customer_total and customer_id. Mind you this field will still require upkeeping although much cheaper.
With this collection you can either $lookup the total (which again can be expensive).

Count and range MongoDB

Let´s say I have a bunch of documents in this format;
{Person: "X" , Note: 4}
What I need to do is to count the total of Person who has the field Note within the range 0 - 50, 51-100, 101-150 and 150 or more
Something like this
//range of Note //total of persons in this range
0-50 14
51-100 32
101-150 34
151 21
In MongoDb you have $lt and $gt commands through which you can get less then and greater then values.
Then you can use $count on it like this->
db.table.aggregate(
[
{
$match: {
Note: {
$gt: 0, $lt: 50
}
}
},
{
$count: "0-50"
}
]
)
It will show result like:
{ "0-50" : 14 }

Mongo $geoNear not searching in all records

I'm wondering if anyone can help me solve a problem with this query.
I'm trying to query all my items with a $geoNear operator but with a very large maxDistance it doesn't seem to search in all records.
The logs show this error "Too many geoNear results for query" which apparently means that the query hit the 16MB limit, but the output is only 20 records and claims the total is 1401 where I would expect 17507 as total.
The average record is 12345 bytes. At 1401 records it stops because it hit 16MB limit.
How can I run this query so that it returns the first 20 results taken from the entire pool of items?
This is the query I'm running:
db.getCollection('items').aggregate([
{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [
10,
30
]
},
"minDistance": 0,
"maxDistance": 100000,
"spherical": true,
"distanceField": "location",
"limit": 100000
}
},
{
"$sort": {
"createdAt": -1
}
},
{
"$facet": {
"results": [
{
"$skip": 0
},
{
"$limit": 20
}
],
"total": [
{
"$count": "total"
}
]
}
}
])
This is the output of the query (and the error is added to the log):
{
"results" : [
// 20 items
],
"total" : [
{
"total" : 1401
}
]
}
I changed my query to use a separate find() and count() call. The facet was severely slowing down the query and since it really isn't a complex query, there was no reason to use an aggregate.
I initially used the aggregate because it made sense to do 1 db call instead of multiple and with $facet you'd have built in paging with a total count but it 1 aggregate call took 600ms where as now a find() and count() call take 20ms.
The 16MB limit is also no problem anymore.

MongoDB - Querying between a time range of hours

I have a MongoDB datastore set up with location data stored like this:
{
"_id" : ObjectId("51d3e161ce87bb000792dc8d"),
"datetime_recorded" : ISODate("2013-07-03T05:35:13Z"),
"loc" : {
"coordinates" : [
0.297716,
18.050614
],
"type" : "Point"
},
"vid" : "11111-22222-33333-44444"
}
I'd like to be able to perform a query similar to the date range example but instead on a time range. i.e. Retrieve all points recorded between 12AM and 4PM (can be done with 1200 and 1600 24 hour time as well).
e.g.
With points:
"datetime_recorded" : ISODate("2013-05-01T12:35:13Z"),
"datetime_recorded" : ISODate("2013-06-20T05:35:13Z"),
"datetime_recorded" : ISODate("2013-01-17T07:35:13Z"),
"datetime_recorded" : ISODate("2013-04-03T15:35:13Z"),
a query
db.points.find({'datetime_recorded': {
$gte: Date(1200 hours),
$lt: Date(1600 hours)}
});
would yield only the first and last point.
Is this possible? Or would I have to do it for every day?
Well, the best way to solve this is to store the minutes separately as well. But you can get around this with the aggregation framework, although that is not going to be very fast:
db.so.aggregate( [
{ $project: {
loc: 1,
vid: 1,
datetime_recorded: 1,
minutes: { $add: [
{ $multiply: [ { $hour: '$datetime_recorded' }, 60 ] },
{ $minute: '$datetime_recorded' }
] }
} },
{ $match: { 'minutes' : { $gte : 12 * 60, $lt : 16 * 60 } } }
] );
In the first step $project, we calculate the minutes from hour * 60 + min which we then match against in the second step: $match.
Adding an answer since I disagree with the other answers in that even though there are great things you can do with the aggregation framework, this really is not an optimal way to perform this type of query.
If your identified application usage pattern is that you rely on querying for "hours" or other times of the day without wanting to look at the "date" part, then you are far better off storing that as a numeric value in the document. Something like "milliseconds from start of day" would be granular enough for as many purposes as a BSON Date, but of course gives better performance without the need to compute for every document.
Set Up
This does require some set-up in that you need to add the new fields to your existing documents and make sure you add these on all new documents within your code. A simple conversion process might be:
MongoDB 4.2 and upwards
This can actually be done in a single request due to aggregation operations being allowed in "update" statements now.
db.collection.updateMany(
{},
[{ "$set": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$datetime_recorded" },
1000 * 60 * 60 * 24
]
}
}}]
)
Older MongoDB
var batch = [];
db.collection.find({ "timeOfDay": { "$exists": false } }).forEach(doc => {
batch.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": {
"$set": {
"timeOfDay": doc.datetime_recorded.valueOf() % (60 * 60 * 24 * 1000)
}
}
}
});
// write once only per reasonable batch size
if ( batch.length >= 1000 ) {
db.collection.bulkWrite(batch);
batch = [];
}
})
if ( batch.length > 0 ) {
db.collection.bulkWrite(batch);
batch = [];
}
If you can afford to write to a new collection, then looping and rewriting would not be required:
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$subtract": [ "$datetime_recorded", Date(0) ] },
1000 * 60 * 60 * 24
]
}
}},
{ "$out": "newcollection" }
])
Or with MongoDB 4.0 and upwards:
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$datetime_recorded" },
1000 * 60 * 60 * 24
]
}
}},
{ "$out": "newcollection" }
])
All using the same basic conversion of:
1000 milliseconds in a second
60 seconds in a minute
60 minutes in an hour
24 hours a day
The modulo from the numeric milliseconds since epoch which is actually the value internally stored as a BSON date is the simple thing to extract as the current milliseconds in the day.
Query
Querying is then really simple, and as per the question example:
db.collection.find({
"timeOfDay": {
"$gte": 12 * 60 * 60 * 1000, "$lt": 16 * 60 * 60 * 1000
}
})
Of course using the same time scale conversion from hours into milliseconds to match the stored format. But just like before you can make this whatever scale you actually need.
Most importantly, as real document properties which don't rely on computation at run-time, you can place an index on this:
db.collection.createIndex({ "timeOfDay": 1 })
So not only is this negating run-time overhead for calculating, but also with an index you can avoid collection scans as outlined on the linked page on indexing for MongoDB.
For optimal performance you never want to calculate such things as in any real world scale it simply takes an order of magnitude longer to process all documents in the collection just to work out which ones you want than to simply reference an index and only fetch those documents.
The aggregation framework may just be able to help you rewrite the documents here, but it really should not be used as a production system method of returning such data. Store the times separately.