Home >Database >Mysql Tutorial >Detailed introduction to common operations of MongoDB
MongoDB is written in C++ language and is an open source database system based on distributed file storage. Under high load conditions, adding more nodes can ensure server performance. MongoDB aims to provide scalable, high-performance data storage solutions for WEB applications.
1. Add, delete, modify and query
View all collections in the current database, use the command
show collections 或使用 show tables
There are two ways to create a collection, display the creation and Implicit creation
显示创建可以使用命令 db.createCollection(“集合名称") 隐式创建可以使用命令 db.集合名称.insert({}), 指创建集合并同时向集合中插入数据, 例如:db.customer.insert({name:”jack”})
Add documents to the collection
Use the command db.collectionname.insert({}), for example:
db.user1.insert({name:”jack”,age:20})
Delete documents in the collection
使用命令 db.集合名称.remove({删除条件}), 不加删除条件为删除集合中的所有文档: 例如,删除c1集合中的所有文档 db.c1.remove() 删除c1集合中name为user1的文档 db.c1.remove({name:”user1”})
Query the documents in the collection
db.集合名称.find({条件}) 或者使用 db.集合名称.findOne() 查询第一个文档
Query the documents in the collection and return certain key values
In addition to query expressions, MongoDB also supports some additional parameter options.
If you only want to return certain field values:
Return all fields except the age field
db.user.find({},{age:0});
Return all columns with tags=tennis except comments
db.posts.find({tags:'tennis'},{comments:0});
Return the name field with userid=16
db.user.find({userid:16},{name:1});
{"_id":16,"name":"user16"}
Return all z's of x=john Field
db.things.find({x:"john"},{z:1});
Query documents in the collection, use conditional expressions (cdf98572887b2c0e8ee7a799db6e5a4c=,!=)
//Greater than: field > value
db.collection.find({field:{$gt:value}});
//Less than : field a03dcd0d2117962c65e9a3c11db9ce82= value
db.collection.find ({field:{$gte:value}});
//Less than or equal to: field <= value
db.collection.find({field:{$lte:value}});
//Not equal to: field != value
db.collection.find({field:{$ne:value}});
Query documents in the collection, statistics ( count), sort (sort), paging (skip, limit)
db.customer.count(); db.customer.find().count(); db.customer.find({age:{$lt:5}}).count(); db.customer.find().sort({age:1}); 降序-1 db.customer.find().skip(2).limit(3); db.customer.find().sort({age:-1}).skip(2).limit(3); db.customer.find().sort({age:-1}).skip(2).limit(3).count(); db.customer.find().sort({age:-1}).skip(2).limit(3).count(0); db.customer.find().sort({age:-1}).skip(2).limit(3).count(1);
Query the documents in the collection
$all is mainly used to query the documents in the array Inclusion relationship,
As long as one of the query conditions is not included,
$in will not be returned, similar to IN$nin in
relational database, and $in is the opposite of
$or, which is equivalent to OR in a relational database, indicating an or relationship.
For example, to query documents with name user2 or age 3, the command is:
db.customer .find({$or:[{name:”user2”},{age:3}]})
$nor, which means filtering out certain data based on conditions, for example, query name is not user2, age is not 3 document, the command is:
db.customer.find({$nor:[{name:”user2”},{age:3}]})
$exists, used to query the collection Documents where a certain key exists or documents where a certain key does not exist. For example, to query all documents with the name key in the customer collection, you can use
db.customer.find({name:{$exists:1}})
$exists:1 means true, which means it exists.
$exists:0 means false, which means it does not exist.
Cursor
Update documents in the collection
Syntax: db.collection.update(criteria,objNew,upsert,multi)
Parameter description:
criteria: Object used to set query conditions
objNew: used to set Object to update content
upsert: If the record already exists, update it, otherwise add a new record, the value is 0 or 1
multi: If there are multiple records that meet the conditions, whether to update them all, the value is 0 or 1
Note: By default, only the first record that meets the conditions will be updated
Generally, the last two parameters are 0 and 1 respectively, that is:
db.collection. update(criteria,objNew,0,1)
Change the document with name user1 in the collection to name jack:
db.c1.update({name:"user1"},{name: "jack"})
$set is used to specify the value of a key. If the key does not exist, create it. For example:
To add address to the document named user1, you can use the command:
db.c1.update({name:”user1”},{$set:{address:”bj”}},0, 1)
Change the address of the document named user1 to tj, Other key-value pairs remain unchanged, the command is:
db.c1.update({name:”user1”},{ $set:{address:”tj”}},0,1)
Use $inc to add 1 to the age named user1 in the set, leaving other keys unchanged.
$inc means to make a certain Add or subtract the specified value from the key value
db.c1.update({name:"user1"},{$inc:{age:1}})
$unset is used to delete a key
For example, to delete the address key in the document named user1, you can use the command:
db.c1.update({name:”user1”},{$unset:{address:1}},0,1)
2. Index:
Indexes are used to speed up queries. A database index is similar to a book index: with an index, you don't need to look through the entire book, but the database can search directly in the index, making the search speed faster by several orders of magnitude. Once an entry is found in the index, you can jump directly to the location of the target document.
Normal index:
Create: db.collection.ensureIndex({key:1})
View related information about the index: db.collection.stats()
View the index used by the query Situation: db.collection.find({key:value}).explain()
Delete index: db.collection.dropIndex({key:1})
Deleting the collection will also delete the index in the collection Delete all
Unique index:
Create:db.collection.ensureIndex({key:1},{unique:true})
View related information about the index:db.collection.stats( )
View the query using the index: db.collection.find({key:value}).explain()
Delete the index: db.collection.dropIndex({key:1})
Delete the collection , all indexes in the collection will also be deleted
3. Capped collection
A fixed collection refers to a collection that is created in advance and has a fixed size.
Fixed collection features: Fixed collections are much like ring queues. If there is insufficient space, the oldest documents will be deleted to make room for new documents. Generally speaking, fixed collections are suitable for any scenario where you want to automatically eliminate expired attributes without too many operational restrictions.
Create a fixed collection:
db.createCollection("collectionName",{capped:true,size:100000,max:100});
size specifies the collection size, the unit is KB, max specifies Number of documents
When specifying the upper limit of the number of documents, the size must also be specified. The elimination mechanism only works based on the number of documents when the capacity is not full. If the capacity is full, the elimination mechanism will work based on the capacity.
4. Backup (mongodump) and recovery (mongorestore)
MongoDB provides backup and recovery functions, which are mongodump.exe and mongorestore in the MongoDB download directory. .exe file (that is, the command in the mongodb bin directory)
To back up data, use the following command:
mongodump -h dbhost -d dbname -o dbdirectory
-h: The server address where MongoDB is located, For example: 127.0.0.1, of course you can also specify the port number: 127.0.0.1:27017
-d: the database instance that needs to be backed up, for example: test
-o: the backup data storage location, for example: c:\ data\dump. Of course, this directory needs to be created
in advance. After the backup is completed, the system automatically creates a test directory under the dump directory. This
directory stores the backup data of the database instance.
To restore data, use the following command:
mongorestore -h dbhost -d dbname -directoryperdb dbdirectory
-h: MongoDB server address
-d: The database instance that needs to be restored, for example: test, of course, this name can also be different from the one used during backup, such as test2
-directoryperdb: the location of the backup data, for example: c:\data\dump\test
5. Import ( mongoimport) and export (mongoexport)
To export data, you can use the command:
mongoexport -h dbhost -d dbname -c collectionName -o output
Parameter description:
-h database Address
-d Specifies the library used
-c Specifies the collection to be exported
-o Specifies the file name to be exported
Example:
mongoexport -h localhost:27017 -d test -c c4 -o d:/beifeng/c4.txt
To import data, you can use the command:
mongoimport -h dbhost -d dbname -c collectionname The address of the file...
Parameter description:
-h Database address
-d Specifies the library used
-c Specifies the collection to be imported
Local file address...
Example:
mongoimport -h localhost:27017 -d test -c cctv d:/beifeng/c4.txt
The above is the detailed content of Detailed introduction to common operations of MongoDB. For more information, please follow other related articles on the PHP Chinese website!