MongoDB data query method dry article

  • 2020-06-12 10:54:32
  • OfStack

This article mainly introduces MongoDB data query related content, has a certain reference value for you, friends in need of 1 up to learn to learn.

Import test data

Before we start, we should prepare the data for demonstration. Here I inserted several pieces of data, which are as follows:


db.user.insertMany(
[{
name:'jack',
age:22,
sex:'Man',
tags:['python','c++','c'],
grades:[22,33,44,55],
school:{
name:'shida',
city:'xuzhou'
}
},{
name:'jhon',
age:33,
sex:null,
tags:['python','java'],
grades:[66,22,44,88],
school:{
name:'kuangda',
city:'xuzhou'
}
},
{
name:'xiaoming',
age:33,
tags:['python','java'],
grades:[66,22,44,88],
school:{
name:'kuangda',
city:'xuzhou'
}
}
]
)

find()

Where query represents the criteria for finding, which is equivalent to the where clause in mysql, which lists the data you want to find in the format of db.collection.find(find(<query filter>, <projection>))

Example:

The following lookup without parameters will find all the results


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}

Now find the data that satisfies name as jack, and output only name,age, here _id is the default output, set it to 0 if you don't want to output, set it to 1 if you want to output that field


db.user.find({name:'jack'},{name:1,age:1})
// The output 
{ "_id" : ObjectId("59056f81299fe049404b2899"), "name" : "jack", "age" : 22 }
db.user.find({name:'jack'},{name:1,age:1 . _id:0})
// The output 
{"name" : "jack", "age" : 22 }

** Note: An projection cannot specify both include and exclude fields, except for the _id field. In mappings that explicitly include fields, the _id field is the only 11 you can explicitly exclude.

Query embedded documents

The school data inserted in the above example represents the embedded document

Perfectly matched query

A perfect match query means that the query array in school must be exactly the same as the inserted array, in order to be found


db.user.find({name:'jack',school:{name:'shida',city:'xuzhou'}});
// The output 
{ "_id" : ObjectId("59056f81299fe049404b2899"), "name" : "jack", "age" : 22, "tags" : [ "python", "c++", "c" ], "grades" : [ 22, 33, 44, 55 ], "school" : { "name" : "shida", "city" : "xuzhou" } }
// Below is the specified output field, here school.name Means output only school In the document name Fields must be quoted 
db.user.find({name:'jack',school:{name:'shida',city:'xuzhou'}},{name:1,age:1,'school.name':1});
// The output 
{ "_id" : ObjectId("59056f81299fe049404b2899"), "name" : "jack", "age" : 22, "school" : { "name" : "shida" } }

Key-value pair queries

You can query by key-value pair, regardless of order, for example 'school.name':'shida' , which is required to query the data for the name of the school shida


db.user.find({'school.name':'shida'},{name:1,school:1});
// The output 
{ "_id" : ObjectId("59056f81299fe049404b2899"), "name" : "jack", "school" : { "name" : "shida", "city" : "xuzhou" } }

Query operator

We will now cooperate with the query operators to perform complex query operations, such as element query, logical query, and comparison query operations. We use the following comparison operators "$gt", "$gte", "$lt", "$lte"(for each" > "," > = "," < "," < =")

The instance

The following query is for information between ages 20 and 30


db.user.find({
age:{$gt:20,$lt:30} 
})
// The output 
{ "_id" : ObjectId("59056f81299fe049404b2899"), "name" : "jack", "age" : 22, "tags" : [ "python", "c++", "c" ], "grades" : [ 22, 33, 44, 55 ], "school" : { "name" : "shida", "city" : "xuzhou" } }

$ne

$ne indicates inequality, such as asking for information that age does not equal 22 years


db.user.find({age:{$ne:22}})
// The output 
{ "_id" : ObjectId("59057c16f551d8c9003d31e0"), "name" : "jhon", "age" : 33, "tags" : [ "python", "java" ], "grades" : [ 66, 22, 44, 88 ], "school" : { "name" : "kuangda", "city" : "xuzhou" } }

slice

The $slice operator controls the number of elements in the array returned by the query. This operator is based on parameters { field: value } Specify the key name and key value to select the document collection, and the array key specified in that document collection will return the number of elements from the specified number. If the value of count is greater than the number of elements in the array, the query returns the values of all elements in the array.

Grammar: db.collection.find( { field: value }, { array: {$slice: count }});

The first two Numbers in grades are queried


db.user.find({name:'jack'},{grades:{$slice:2},name:1,age:1,'school.name':1});
// The output, you can see here grades Only the first two are printed 
{ "_id" : ObjectId("59057c16f551d8c9003d31df"), "name" : "jack", "age" : 22, "grades" : [ 22, 33 ], "school" : { "name" : "shida" } }

The last three are output below


db.user.find({name:'jhon'},{grades:{$slice:-3},name:1});
// The output 
{ "_id" : ObjectId("59057c16f551d8c9003d31e0"), "name" : "jhon", "grades" : [ 22, 44, 88 ] }

The following description specifies 1 array as the argument. Array parameter use [ skip , limit ] Format, where the first value represents the number of items skipped in the array and the second value represents the number of items returned.


db.user.find({name:'jack'},{grades:{$slice:[2,2]},name:1}); // I'm going to skip the first two and go straight to the next two 
// The output 
{ "_id" : ObjectId("59057c16f551d8c9003d31df"), "name" : "jack", "grades" : [ 44, 55 ] }

$exists
If the value of $exists is true, select the document that contains the field, or if the value is false, select the document that does not contain the field

The following will query for information where the item sex does not exist


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
0

$or

Perform the logical OR operation, specify an array of at least two expressions, and select a document that satisfies at least one expression in the array.

Grammar: { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

We're going to look for age equals 22 or age equals 33


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
1

Below you will find the information for a person aged 22 or 33 with the name jack


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
2

$and

Specify an array of at least two expressions, and select the document that satisfies all the expressions in the array. The $and operator USES a short-circuit operation. If the value of the first expression is "false", the rest of the expression will not be executed.

Grammar: { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

For the following list of comma-delimited expressions, MongoDB provides an implicit $and operation:


db.user.find({$and:[{age:{$gt:20}},{age:{$lt:30}}]})
// The above statement is equivalent to db.user.find({age:{$gt:20},age:{$lt:30}})
// The results of 
{ "_id" : ObjectId("59058460fe58ed1089f2a5cb"), "name" : "jack", "age" : 22, "sex" : "Man", "tags" : [ "python", "c++", "c" ], "grades" : [ 22, 33, 44, 55 ], "school" : { "name" : "shida", "city" : "xuzhou" } }

$in

Matches a document whose key value is equal to any value in the specified array. Similar to in in sql, as long as 1 value is matched, it will output

Grammar: { field: { $in: [<value1>, <value2>, ... <valueN> ] } }

The following will look for any number between 22 and 33 in grades


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
4

$nin

A document that matches a key that does not exist or whose key value is not equal to any value of the specified array. Similar to sql not in(SQL field has no syntax error).

Query grades to find that there are no documents of 100 or 44


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
5

$not

Perform the logical NOT operation to select documents that do not match the expression, including those without a specified key. The $not operator cannot be used independently and must be used in conjunction with other operations 1

Grammar: { field: { $not: { } } }

Search for information with an age of 30 or less


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
6

Iterate over the query of the cursor

Those of you who have learned a high-level language know the problem of iteration, like java, and use iterative methods to query


 db.find().pretty();
 
 // The output 
 
 
{    
 "_id" : ObjectId("59056f81299fe049404b2899"), 
 "name" : "jack",  
 "age" : 22,   
 "tags" : [   
 "python",  
 "c++",  
 "c"   
 ],   
 "grades" : [   
 22,   
 33,   
 44,   
 55   
 ],   
 "school" : {   
 "name" : "shida",  
 "city" : "xuzhou"  
 }   
}
7

conclusion


Related articles: