What is MongoDB?
MongoDB is an open source database system based on distributed file storage written in C++ language. MongoDB stores data as a document. The data structure consists of key=>value pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays, and document arrays.
Download and install
MongoDB provides pre-compiled binaries for both 32-bit and 64-bit systems. You can download the pre-compiled binaries from the MongoDB website at www.mongodb.com/download-ce…
My MongoDB is installed in the D:\ MongoDB directory, after installation, go to the installation directory D:\ MongoDB \data, create a new database directory, such as DB
The mongodb server is started
Absolute road power way to start
Open the Cmder command line tool, which I have been using, and type D:\mongodb\bin\mongod –dbpath D:\mongodb\data\db and press Enter
Mongod command to start
After the bin directory Path is configured, you can directly start the server by running mongod –dbpath D:\mongodb\data\db or mongod — dbpath.\ db in the data directory
The bin Path Path is specified
In order to start mongodb convenient, will mongod. Exe Path to add environment variables, location: computer -> Properties -> Advanced System Settings -> Environment variables, in the Path of system variables, at the end of the installation of mongodb bin directory, remember to add English semicolon ‘; ‘. Once everything is saved, reopen the command line window and you can use the mongod command and other commands in the bin directory anywhere
Client connection
After starting the server, do not close the command line window on the server side. You need to reopen a command line window and type mongo in any directory to start the client (if “‘mongo’ is not an internal or external command, nor is it a runnable program or batch file). , please configure the above Path Path); If you just don’t want to configure the Path, go to the bin directory of your installation directory and double-click mongo.exe to open the client directly
MongoDB Concept Analysis
The basic concepts in mongodb are documents, collections, and databases
- Database: Multiple databases can be created in one mongodb; The default MongoDB database is “DB”, which is stored in the data directory. Use show DBS to view all databases
- Collections: Collections are groups of MongoDB documents, similar to tables in an RDBMS. Collections exist in databases, and collections have no fixed structure, which means you can insert different formats and types of data into collections. use
show collections
, you can view all collections under the current database instance - Documents: A document is a set of key-value pairs (that is, BSons). MongoDB documents do not need to have the same fields set, and the same fields do not need the same data types. use
db.collection.find()
Command to view all documents under the collection
Database (DB)
When you connect to the client for the first time, run the db command to check database test by default. Then run the show DBS command to check all databases, and run the use command to switch databases, for example, use admin to switch to the admin database
> db
test
> show dbs
admin 0.000GB
config 0.000GB
local0.000 GB school 0.000 GBtest 0.000GB
> use admin
switched to db admin
Copy the code
Creating a Database
The syntax for creating a database is: Create a new database. For example, use ORDER to create a new database, but show DBS does not find the database. Insert (db.info.insert({‘name’:’ three ‘,’note’:’hello world’})) Then use show DBS to see the order database
> use order
switched to db order
> db
order
> show dbs
admin 0.000GB
config 0.000GB
local0.000 GB school 0.000 GBtest0.000 GB > db. Info. Insert ({'name':'Joe'.'note':'hello world'})
WriteResult({ "nInserted": 1}) > show DBS admin 0.000GB config 0.000GBlocalOrder 0.000GB School 0.000GBtest0.000 GBCopy the code
Deleting a Database
Mysql > delete school from db dropDatabase(); mysql > delete school from db dropDatabase(); mysql > delete school from db dropDatabase(); I tried it, but it didn’t work.
> use school
switched to db school
> db
school
> db.dropDatabase()
{ "dropped" : "school"."ok": 1} > show DBS admin 0.000GB config 0.000GBlocal0.000 GB order 0.000 GBtest0.000 GBCopy the code
Collection
Create a collection
The syntax for creating a collection is db.createcollection (name, options). The first parameter name is the mandatory collection name, and the second options is an optional parameter specifying the memory size and index options, for example, We use the command db.createcollection (‘goods’) to create a new collection of goods under the Order database, and then use the show Collections or show tables commands to view the documents under that database
> use order
switched to db order
> db.createCollection('goods')
{ "ok" : 1 }
> show collections
goods
info
> show tables
goods
info
Copy the code
Can we not create a collection beforehand?
Of course you can, but in MongoDB, you don’t need to create a collection first, because when you insert a document, MongoDB will automatically create the collection, for example, We use db.user.insert({‘name’:’lisan’,’age’:23,’sex’:’w’}) to create a user set in the order database and insert a document
> show tables
goods
info
> db.user.insert({'name':'lisan'.'age': 23.'sex':'w'})
WriteResult({ "nInserted" : 1 })
> show collections
goods
info
user
Copy the code
Delete the collection
Db.collectionname.drop (); for example, we use db.user.drop() to drop the user collection we just created
> db.user.drop()
true
> show collections
goods
info
Copy the code
Db.goods.help (); db.goods.help(); db.goods.help();
Document
Inserted into the document
MongoDB uses the insert() method to insert documents into the collection with the syntax db.collectionName.insert(document), Insert ({‘name’:’ product name’,’price’:123,’sale’:6}) into the goods collection. And the _id value must be unique, default is objectId())
> db.goods.insert({'name':'Trade Name'.'price': 123,'sale':6})
WriteResult({ "nInserted": 1})Copy the code
Other methods for inserting documents
Inserted into the document, or you can use the db. CollectionName. InsertOne (insert a document) or use the db. CollectionName. InsertMany (document) insert multiple, InsertOne () is used just like insert(), document is a JSON object; When insertMany() inserts multiple objects, document is an array of json objects, as shown in the following example:
> db.goods.insertOne({'name':'Commodity Name 6'.'price': 19,'sale'9} :))))"acknowledged" : true."insertedId" : ObjectId("5e953450aabbbfa8f930a967")
}
> db.goods.insertMany([{'name':'Commodity Name 88'.'price': 18.'sale': 1}, {'name':'Commodity Name 99'.'price': 99,'sale': 99}])))"acknowledged" : true."insertedIds" : [
ObjectId("5e953475aabbbfa8f930a968"),
ObjectId("5e953475aabbbfa8f930a969")]}Copy the code
Alternatively, you can insert documents using the db.collectionName.save(document) command. The save() method is similar to the INSERT () method if the _ID field is not specified. If the _id field is specified, the _id data is updated.
Update the document
MongoDB uses the update() method to update documents in the collection, with the following syntax:
db.collectionName.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
Copy the code
{‘name’:’ product name 6′,’price’:19,’sale’:9} Db.goods. update({‘name’:’ goods. 6′}, {$set:{‘price’:91}}
> db.goods.find()
{ "_id" : ObjectId("5e95322caabbbfa8f930a965"), "name" : "Trade Name"."price" : 123, "sale": 6} {"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Commodity Name 6"."price" : 19, "sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Commodity Name 88"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale" : 99 }
> db.goods.update({'name':'Commodity Name 6'}, {$set: {'price':91}})
WriteResult({ "nMatched" : 1, "nUpserted": 0."nModified" : 1 })
> db.goods.find() 1}})
{ "_id" : ObjectId("5e95322caabbbfa8f930a965"), "name" : "Trade Name"."price" : 123, "sale": 6} {"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Commodity Name 6"."price" : 91, "sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Commodity Name 88"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99}Copy the code
You can also replace an existing document with an incoming document by using the save() method, and you must pass in the value of the _id
Partial update operator
In the above update command, you might ask $set what does that mean? This is the operator that sets the value of a field in the document. There are many other update operators, as outlined below:
- $unset: Deletes the specified field
- $inc: Adds the specified value to a field
- $pop: Removes the first or last element in an array field
- $push: Appends a value to the array
- $pushAll: Appends multiple specified values to an array
- $pull: The value that meets the condition will be deleted
- Other……
Other updates document description
Update () by default will only update the first item that meets the criteria. If you want to update all of the items, you need to set the multi value to true. Both numbers have changed
> db.goods.find() e}})
{ "_id" : ObjectId("5e95322caabbbfa8f930a965"), "name" : "Trade Name"."price" : 123, "sale": 6} {"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Commodity Name 6"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Commodity Name 88"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale" : 99 }
> db.goods.update({'price': 18}, {$set: {'name':'Same trade name'}}, {multi: true})
WriteResult({ "nMatched": 2."nUpserted": 0."nModified" : 2 })
> db.goods.find() true{})"_id" : ObjectId("5e95322caabbbfa8f930a965"), "name" : "Trade Name"."price" : 123, "sale": 6} {"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Same trade name"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99}Copy the code
And, at the beginning of the 3.2 version, directing also provides the collectionName. UpdateOne () to update a document, the collectionName. UpdateMany () to update multiple documents, and update a single and update the same, in the first two parameters, Using updateMany() to update multiple is more convenient, without passing the multi true
Delete the document
MongoDB uses remove() to remove documents, with the following syntax
db.collectionName.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
Copy the code
Remove db.goods.remove({‘goods’: ‘goods’}); remove({‘goods’: ‘goods’});
> db.goods.remove({'name': 'Trade Name'}))
WriteResult({ "nRemoved" : 1 })
> db.goods.find()
{ "_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Same trade name"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99}Copy the code
Other documents to be deleted
-
Remove ({‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: {‘goods’: ‘goods name ‘}, 2), if you want to delete the entire document of the collection and pass in an empty object, db.goods.remove({})
-
The remove() method is obsolete, and deleteOne() is now officially recommended to delete individual documents and delete; DeleteOne ({‘goods’: ‘goods’) db.goods.deleteone ({‘goods’: ‘goods’) db.goods.deletemany ({‘goods’: ‘goods’: ‘goods’})
Query the document
Find (query, projection). Both parameters are optional (query is the query condition and projection is the return field). Db.goods.find () db.goods.find()
> db.goods.find()
{ "_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Same trade name"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99} find db.goods.find({goods set sale > 6;'sale': {$gt: 6}})
> db.goods.find({'sale': {$gt: {6}})"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale"Db.goods. find({goods set sale > 6 and price < 20}'sale': {$gt: 6}, 'price': {$lt: 20}})
> db.goods.find({'sale': {$gt: 6}, 'price': {$lt: 20} {})"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale"9} :Copy the code
Description of conditional operators
$gt ($lt); $gt ($lt);
- $gt: Finds documents with field values greater than the specified value
- $lt: Finds documents with field values less than the specified value
- $gTE: Finds documents with field values greater than or equal to the specified value
- $LTE: Finds documents with field values less than or equal to the specified value
- $IN: Find a field value equal to any value in the specified array
- $nin: The field value is not in the specified array or does not exist
- $or: The document satisfies at least one of the expressions
- $eq: Finds documents whose field value is equal to the specified value
- $ne: Finds documents whose field value is not equal to the specified value, including documents that do not have this field
- Other……
Fuzzy query for regular matching
Find ({key:/value/}) for fuzzy queries, MongoDB also supports regular matching
> db.goods.find({'name': / 99 / {}))))"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale" : 99 }
> db.goods.find({'name'$/})) {"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Same trade name"."price": 18."sale" : 1 }
> db.goods.find({'name': /^ merchandise /}) {"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Same trade name"."price": 18."sale": 1} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99}Copy the code
Paging restricted query
Db.collectionname.find ().limit(number); db.collectionname.find ().limit(number);
Limit () returns the first items that meet the criteria. If I want to return the middle items, what should I do? Db.collectionname.find ().limit(number).skip(number)
Db.goods.find ().limit(1).skip(3) db.goods.find().limit(1).skip(3)
> db.goods.find().limit(1).skip(3)
{ "_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99}Copy the code
Sorting query
In MongoDB, sort() method is used to sort data, sort() method can specify the sorted field by parameter, and use 1 and -1 to specify the sorting method, where 1 is ascending and -1 is descending. Db.collectionname.find ().sort({key:1})
Db.goods.find ().sort({‘sale’: 1})
> db.goods.find().sort({'sale': {1})"_id" : ObjectId("5e953475aabbbfa8f930a968"), "name" : "Same trade name"."price": 18."sale": 1} {"_id" : ObjectId("5e95340faabbbfa8f930a966"), "name" : "Commodity Name 1"."price": 19.99."sale": {8}"_id" : ObjectId("5e953450aabbbfa8f930a967"), "name" : "Same trade name"."price": 18."sale": 9} {"_id" : ObjectId("5e953475aabbbfa8f930a969"), "name" : "Commodity Name 99"."price" : 99, "sale": 99}Copy the code
Note: When skip(), limilt(), and sort() are executed together, the order of execution is sort(), then skip(), and then limit().
The last show
Here, I believe you will have the basic usage of MongoDB, if you need to know more, you can find the relevant tutorial and official instructions, if there is wrong or incomplete, please point out, I will correct in time, thank you.