Mongodb in a very good Aggregate
Aggregate translates to aggregate, but in practice it’s very much like the experience of Linux pipes, where each pipe is processed and then the result is handed over to the next pipe, and your data is like water flowing through each pipe to get the data you want
What do we usually do with Aggregate
Aggregate query documents
- Aggregate average and other data processingsum
- Geolocation information $geoNear
- Basically, we can use Aggregate to implement all mongodb query operations
Here I mainly want to record the technology used by mongodb in the query of geographic location information, which can not only query the distance but also can be sorted by distance
$geoNear Geolocation information query
First of all, how to store our coordinate data in the database, the type is Array, remember to add 2d index, of course, and 3D index, which is not used at present
const storeschema = new mongoose.Schema({
name: { type: String.required: true },
point: { type: Array.required: true }, // [lon, lat]
});
storeschema.index({ point: '2d' });
return mongoose.model('store', storechema);
Copy the code
Then follow the geographic query code
this.ctx.model.Store.aggregate([{
$geoNear: {
spherical: true.// Whether the distance is determined according to the spherical shape
distanceMultiplier: 6378137.maxDistance: 10000.near: [ lon1, lat1 ],
distanceField: 'dist'.key: 'point'.query: {}},},//distanceMultiplier is used to determine the distance you have returned in units. 6378137 is in m
//maxDistance Specifies the maximum query distance
// Near the center point
// distanceField which attribute to place the distance in
// key where coordinate data is stored
// query your filter criteria
Copy the code
One of the interesting things about this is thatMatch so there’s a query property here to make up for this regret
However, you can use $match later to filter all the geolocation data again
$lookup join table query in mongodb
$lookup is an attribute that can only be used in newer mongodb versions. This attribute is also used in aggregate, which makes up for the inability to join tables in mongodb
Look at the code
await this.ctx.model.MemberInfo.aggregate([
{
$match: { store: new ObjectId(store) }
},
{
$lookup: {
from: 'users'.localField: 'user'.foreignField: '_id'.as: 'user'}}, {$replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: [ '$user'.0]},'? ROOT'}}}, {$match: { 'certification.name': { $regex: search } }
},
{
$project: { _id: 1}}]);Copy the code
LocalField: ‘user’ is the foreign key corresponding to the user table foreignField: ‘_id’.
To be clear, I only save the user’S ID in my membership form. Now I want to get the user’s other information…
Attach the link to $lookup
Write in the last
Of course he is querying all kinds of gold and of course he supports defining the output of dataLimit $sort, etc