Mongodb basic operation

Time:2021-10-21

More welcome to the blog:https://imjianjian.github.io


Mongodb version: 3.4

consult your documentation

find()

Query all

db.collection.find({})
db.collection.find()

Document query

//Query all documents with name = "Jian"
db.collection.find({"collection":"jianjian"})

Conditional Operator

  • $LT less than
  • $GT greater than
  • $GTE is greater than or equal to
  • $LTE less than or equal to
  • $ne is not equal to
  • $all inclusive
  • $in contains
  • $Nin does not contain
//Query age less than 18
db.collection.find("age":{$lt:"18"})

$all

All values must be met

//You can find {age: [20,21,22]} but you can't find {age: [20,22,23]}, that is, there must be 20 and 21
db.collection.find({age:{$all:[20,21]}});

$in

This is different from $all. The query value can be found within the range given by $in.

//{age: [20,21,22]}, {age: [20,22,23]} can be found
db.collection.find({age:{$in:[20,21]}});

$exists

Determine whether the key exists

Determine whether the age field exists
db.collection.find({age:{$exists:true}});

Processing of null values

For null value processing, it should be noted that not only records with null value of a field can be queried, but also records without a field can be found.

db.collection.find({age:null})

Records with null age and records without age field can be queried. If we need to query only the records that have the age field and the value of the age field is null, we need to cooperate with the exists operation.

db.collection.find({age:{"$in":[null],"$exists":true}});

Limit the number of queries

limit(number)

Number is the number of entries

//The number of queries is limited to 10
db.collection.find().limit(10)

sort

sort({key:1})

Key is the field to be sorted, with ascending order of 1 and descending order of – 1

//Sort by age in ascending order
db.collection.find().sort({"age":1})

Skip record

skip()

Query the records of items 10 to 20
db.collection.find().skip(10).limit(10);

Number of query documents

count()

Number of pieces with age greater than 25
db.collection.find({age: {$gte: 25}}).count();

Insert document

The basic syntax of insert() is as follows:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Single insert

db.collection.insert({"name":"jianjian"})

Multiple inserts

db.collection.insert([{"name":"jianjian"},{"name":"dongdong"}])

Incorrect syntax

db.collection.insert({"age":11},{"age":12})

Only age: 11 is inserted because the received inserted document is not an array

Misleading:

db.collection.insert([{"name":"jianjian"},{"name":"dongdong"}])

db.collection.insert({"name":"jianjian"},{"age":"dongdong"})

db.collection.insert({"name":"jianjian","name":"dongdong"})

The first one is to insert two documents, the second one is to insert a document, and the third one is also a document, but because the key is repeated, only the latter value will be inserted. Age: 12

remove document

The basic syntax format of the remove () method is as follows:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }

Parameter Description:

  • Query: (optional) the condition of the deleted document.
  • Justone: (optional) if set to true or 1, only one document will be deleted.
  • Writeconcern: (optional) the level at which the exception was thrown.

Delete data with num greater than 100

db.new.remove({"num":{$gt:100}});

Delete all data in the new set

db.new.remove({});

Delete data with num equal to 100

db.new.remove({"num":100})

Update document

The update () method is used to update an existing document. The syntax format is as follows:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

Parameter Description:

  • Query: query criteria of update, similar to the query criteria after where in SQL update query.
  • Update: the update object and some Update Operators (such as $, $Inc…) can also be understood as the object after the set in the SQL update query

Upsert: optional. This parameter means whether to insert objnew if there is no update record. True means insert. The default is false and not insert.

  • Multi: optional. Mongodb is false by default. Only the first record found will be updated. If this parameter is true, all the records found by conditions will be updated.
  • Writeconcern: optional, the level of exception thrown.

$set modifier

Used to modify the value of the key. If the key does not exist, increase the key

//Change the data of age = 10 to 15. By default, if there are multiple records of age = 10, only the first one will be updated
db.collection.update({"name":"li"},{$set:{"age":10}})

//Update multiple qualified values. At the same time, if the updated value does not exist, insert the updated value. Note: the value inserted here is 20, not 30
db.collection.update({"age":30},{$set:{"age":20}},{multi:true,upsert:true})

Multi and upsert can be omitted. Curly braces are not allowed here, but this is not recommended
db.collection.update({"age":30},{$set:{"age":20}},true,true)

//Update value to array
db.collection.update({"name":"zhang"},{$set:{"age":[10,
12,14]}},{upsert:true})

//Change to other values
db.collection.update({"name":"zhang"},{$set:{"age":''}},{upsert:true})
db.collection.update({"name":"zhang"},{$set:{"age":null}},{upsert:true})

$Inc modifier

It is used to increase the value of an existing key. If the key does not exist, it will be created. It can only be used for integer, long integer and floating point types.

//Press the age key of the record with name = Zhang + 10
db.collection.update({"name":"zhang"},{$inc:{"age":10}},{upsert:true})

//Set the age key of the record with name = Zhang to - 10
db.collection.update({"name":"zhang"},{$inc:{"age":-10}},{upsert:true})

$unset modifier

Deleting a key is similar to deleting a field in a relational database. To distinguish between the $set modifier, set the key to null or null

db.collection.update({"name":"zhang"},{$unset:{"age":1}})

$push modifier

If the array already exists, “$push” will add an element to the end of the existing array. If not, a new array will be created. Note: you must be an array to add new values

db.collection.update({"name":"zhang"},{$push:{"comments":{"email":"[email protected]","address":"beijing"}}});

//Insert another comments
db.collection.update({"name":"zhang"},{$push:{"comments":{"mark":"aaa"}}});

$each modifier

Adding elements to an array

db.collection.insert({"title":1,"list":[1,2,3]})

//Adds a single element to the list array
db.collection.update({"title":1},{$push:{"list":4}})

//Add multiple elements to the list array
db.collection.update({"title":1},{$push:{"list":{$each:[6,7]}}});

$addtoset modifier

When inserting elements into the array set, if the elements exist, they will not be inserted; The method is the same as $push. The only difference is that $push does not judge duplicate values, and duplicates can also be inserted$ Addtoset can also be used together with $each. Like $push, you can insert multiple elements into the array at the same time, and if the elements exist, they will not be inserted.

db.collection.update({"title":1},{$addToSet:{"list":2}})

db.collection.update({"title":1},{$addToSet:{"list":{$each:[2,3,4]}}});

$pull modifier

All elements in the matching array will be deleted. Note that only elements in the array can be matched

db.collection.insert({"title":1,"list":[1,2,3]});

//Clear element 2 in list array
db.collection.update({},{$pull:{"list":2}})

$pop modifier

Delete an element from the end or head of the array, $Pop: {“list”: 1}: delete an element from the end$ Pop: {“list”: – 1}: delete an element from the beginning

//Insert two elements into the array list
db.collection.update({},{$push:{"list":{$each:[2,4]}}});

//Delete element from end
db.collection.update({},{$pop:{"list":1}});

//Delete element from beginning
db.collection.update({},{$pop:{"list":-1}});

Position based array modification method
There are two ways to locate elements in an array:

1. Pass the subscript; The subscripts of the array start from 0.

2. Through the $positioning operator,

db.comment.insert({"title":1,"comments":[{"comment":"a","author":"chen","age":10},{"comment":"b","author":"wang","age":30},{"comment":"c","author":"zhang","age":40}]});
//Change the age value of the first list in the array to 20
//Method 1:
db.comment.update({},{$set:{"comments.0.age":20}});

//Method 2:
db.comment.update({"comments.author":"chen"},{$set:{"comments.$.age":20}});

Indexes

Index can greatly improve the efficiency of query. If there is no index, mongodb must scan each file in the collection and select those records that meet the query conditions when reading data.

The query efficiency of scanning the whole collection is very low, especially when processing a large amount of data, the query can take tens of seconds or even minutes, which is very fatal to the performance of the website.

Index is a special data structure. Index is stored in a data set that is easy to traverse and read. Index is a structure that sorts the values of one or more columns in the database table

Ensureindex() method

Mongodb uses the ensureindex () method to create an index.

Set no as index:

db.collection.ensureIndex({"No":1})
1 specifies to create the index in ascending order. If you want to create the index in descending order, specify - 1.

Delete collection

Delete the test set. Note that curly braces are not required in the brackets after drop

db.test.drop()