mongodb database basics associated with table queries
- 2020-12-26 06:00:51
- OfStack
preface
When I was working on my own project, I still kept the influence of the non-relational DATABASE of mongodb and the relational database in my mind at the very beginning. I always wanted to conduct a linked table query, and then Read the official website and materials to learn about it. In addition, I used regularness to match the query, so I made a record here
1.mongodb regular matching
/* use $regex Field matching */
name: {$regex: 'aa', $options: 'i'};
Or:
name: {$regex: /aa/, $options: 'i'};
Or:
name: {$regex: /aa/i};
/* Use expressions directly */
name: {/aa/i}
/* use $in To match, this field must be 1 An array */
name: {$in: [/aa/]}
2. Connect table query
Use $lookup for the join table query
/* aggregate The aggregation operation, $unwind Split the array into individual elements
* $group Group by
* $sum statistical
* $project Filter the return value to return a field after filtering
* $match Matching conditions
* */
usingRecord.aggregate([
{
$lookup: {
from: 'resources', /* The name of the table to join */
localField: 'resource_id', /* The field corresponding to the current table */
foreignField: '_id', /* The field of the table to join */
as: 'resourceInfo' /* The name of the field shown in the query result */
},
},
{
$match: {
'user_id': user_id
}
},
{
$unwind: '$resourceInfo'
},
{
$sort: {
_id: -1
}
}
])
3. Summary
The mongodb database is a non-relational, document database, and storing associated data in one document reduces the number of associated queries between tables
After learning online materials and then learning online videos of MOOCS, I felt a lot. At present, I am still a little confused. I will find a better way to achieve data insertion
conclusion