当前位置:网站首页>Mongodb exploration phase [easy to understand]
Mongodb exploration phase [easy to understand]
2022-07-25 09:21:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
1. database
One mongodb Multiple databases can be set up in .
MongoDB The default database is ”db”, The database is stored in data Directory .
MongoDB Can hold multiple independent databases , Each has its own set and permissions , Different databases are also placed in different files .
“show dbs” The command displays a list of all the data . Equate to MySQL show databases;
If you want to view all databases , have access to show dbs command :
db: Default database name ; test: Table name insert: The insert find: Query operation
perform “db” The command can display the current database object or collection .
2.linux platform mongodb Background daemons start
Mongodb You can use the command line and How to profile To start up , The specific command is as follows :
Command line :
[[email protected] mongodb]# ./bin/mongod --dbpath=/data/db The configuration file :
[[email protected] mongodb]# ./bin/mongod -f mongodb.conf But these two methods are launched in the foreground Mongodb process , If Session The window closed ,Mongodb And then the process stops . however Mongodb It also provides a backstage Daemon Mode start , Just add one ”–fork” Parameters can be , It is worth noting that , Yes ”–fork” Parameters must be enabled ”–logpath” Parameters .
As shown below :
[[email protected] mongodb]# ./bin/mongod --dbpath=data/db --fork
--fork has to be used with --logpath
[[email protected] mongodb]# ./bin/mongod --dbpath=data/db --fork --logpath=log/mongodb.log
all output going to: /opt/mongodb/log/mongodb.log
forked process: 3300
[[email protected] mongodb]# daemon Way to start fork Parameters can also be configured in the configuration file , As shown below :
port=27017
dbpath=data/db
logpath=log/mongodb.log
logappend=true
fork=true Then start through the configuration file mongodb Also started in the background :
[[email protected] mongodb]# ./bin/mongod -f mongodb.conf
all output going to: /opt/mongodb/log/mongodb.log
forked process: 3377 3.MongoDB The database is in the form of service Windows In the background
mongod --dbpath d:\mongodb\data\db --logpath d:\mongodb\log\MongoDB.log --install --serviceName "MongoDB" Add directly to the system service , After execution, I will start , Start up is also self starting
Reference resources :windows Next MongoDB Installation , Configuration and startup – Urban fireworks – Blog Garden
4.mongo.cfg file
systemLog:
destination: file
path: D:\softwore\mongodb3\data\log\mongod.log
storage:
dbPath: D:\softwore\mongodb3\data\db5.MongoBooster The graphical interface
NoSQLBooster – The Smartest GUI Tool and IDE for MongoDB
6. use show dbs see , Always only local A database ?
use newdbname ; Switch or create a new set ( Creation time , Only after inserting data , The new set is effective )
Use command “use Database name ”, Just mark that you want to create a new database , But there is actually no data written , therefore mongodb You won't really create a database ; You have to write data under the new database , for example :
db.test.insert({"key":"value"})7.MongoDB Common sentences
use DATABASE_NAME If the database doesn't exist , Then create the database , Otherwise switch to the specified database .
show dbs View all databases
db.dropDatabase() Delete the current database , The default is test, You can use db Command to view the current database name
db.createCollection(name, options) Create set , Similar to tables in a database ,
db.collectionName.drop() Delete the collection
show tables # Alias , show collections The command will be more accurate
db.COLLECTION_NAME.insert(document) Inserted into the document
db.COLLECTION_NAME.save(document) Inserted into the document , The method is obsolete in the new version ,db.collection.insertOne() or db.collection.replaceOne() Instead of
db.collection.insertOne() Insert a document ,3.2 After the new version
db.collection.insertMany() Insert multiple documents ,3.2 After the new version
update() and save() Method to update the document in the collection
db.collection.remove(<query>, <justOne>) MongoDB Delete the document
db.col.remove({}) Delete all data , Similar to the conventional SQL Of truncate command
db.col.find().pretty() Query the document , Read data in an easy to read way
db.col.find({likes : {$gt : 100}}) Greater than operator - $gt
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER) limit Method ,skip Method
db.COLLECTION_NAME.find().sort({KEY:1})
db.collection.createIndex(keys, options) Create index
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION) polymerization (aggregate) It's mainly used to process data ( Such as the statistical average , Make a peace, etc ), And return the calculated data result
mongostat and mongotop monitor MongoDB Operating condition
mongodump Backup
mongorestore recovery
explain() and hint() Common functions for query analysis
db.runtest.find({post_text:/runoob/i}) Regular matching post_text Contained in the runoob Documents ,i Case insensitive use Database name Access to database If the database does not exist , Create database
db Show current database
show dbs Display the database with non empty content
db.createCollection(' Table name ') Create an unlimited length table
db.createCollection(' Table name ' ,{capped:true,size:1000}) Create a table with limited length
db. Table name .drop() Delete the collection
show collections Show all tables
db. Table name .find() Look up table data
db. Table name .find({ Name : data 1}) Query by criteria
db. Table name .find({ Name : data 1}).pretty() pretty() Format the result of tape search , It is easier to see the structure and content
db. Table name .findOne({ Name : data 1}) Query by criteria , Only return to the first
db. Table name .update({ Name : data 1},{ Name : data 2}) Find data 1 , Replace with data 2
db. Table name .update({ Name : data 1},{$set:{ Name : data 2}}) Find the column as data 1 Of , Replace all data 1 For data 2
db. Table name .remove({ Name : data 1},{justOne:true}) Delete data 1 The line of ,justOne by true Delete 1 strip , by false Delete multiple items when
Comparison operator :
Less than $lt Less than or equal to lte Greater than gt Greater than or equal to gte It's not equal to ne
Logical operators :
or Or, and you can connect with commas directly in stay ... in
Sort : sort()
db. Table name .find().sort({ Field : Parameters }) Parameter is 1 Ascending Parameter is -1 Descending
Pagination :limit()
db. Table name .find().limit( Parameters ) The parameter is the number of entries obtained
db. Table name .find().skip( Parameters ) The parameter is the number of skips
db. Table name .count({ Name : data 1}) Number of Statistics
db. Table name .find( Name : data 1).distinct(' De duplicate fields ',{ Name : data 2}) Remove duplicates
Backup database
mongodump -h ip Address -d Database name -o Storage location
Recover database
mongorestore -h ip Address -d Database name -dir Storage location 8.MongoDB polymerization
>db.lxwdb.aggregate([{$group:{_id:"$title",num_count:{$sum:1}}}])
{ "_id" : "mongodb_test", "num_count" : 4 }
{ "_id" : "mongodb_test123", "num_count" : 1 }
{ "_id" : "update_mongodb", "num_count" : 1 }
{ "_id" : "MongoDB course ", "num_count" : 2 }
{ "_id" : null, "num_count" : 1 }
> db.lxwdb.find()
{ "_id" : ObjectId("613ef95fd1067f6f0d0d1aaa"), "name" : "newlxw" }
{ "_id" : ObjectId("613f0a50d1067f6f0d0d1aad"), "title" : "MongoDB course ", "description" : "MongoDB It's a Nosql database ", "by" : " Novice tutorial ", "url" : "http://www.runoob.com", "tags" : [ "
mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("613f0a56d1067f6f0d0d1aae"), "title" : "MongoDB course ", "description" : "MongoDB It's a Nosql database ", "by" : " Novice tutorial ", "url" : "http://www.runoob.com", "tags" : [ "
mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("613f0bb70c79827ceaac2d23"), "title" : "update_mongodb" }
{ "_id" : ObjectId("613f0f970c79827ceaac2d27"), "title" : "mongodb_test123" }
{ "_id" : ObjectId("613f0f960c79827ceaac2d26"), "title" : "mongodb_test", "age" : 4 }
{ "_id" : ObjectId("613f16540c79827ceaac2d28"), "title" : "mongodb_test", "age" : 4 }
{ "_id" : ObjectId("613f16ba0c79827ceaac2d29"), "title" : "mongodb_test", "age" : 4 }
{ "_id" : ObjectId("613f16dc0c79827ceaac2d2a"), "title" : "mongodb_test", "age" : 5 } db.lxwdb.aggregate([{$group:{_id:"$title",num_count:{$sum:1}}}])$group: Grouping statistics
_id: As id Field of , Unable to change
num_count: Count the number of this group , Self defined , Can be changed
Through fields title Fields group data , And calculate title The sum of the same values of the fields .
Equate to : select title, count(*) from lxwdb group by title9. problem :Win PHP5.6 Wrong presentation Fatal error: Class ‘MongoClient’ not found
Information searched on the Internet , After looking carefully, I found that the two extension names are different . PHP5.6 need php_mongo.dll instead of php_mongodb.dll. download php_mongo.dll Can be installed .
10.PHP call
header("Content-Type: text/html; charset=utf-8");
$m = new MongoClient(); // The default connection host and port is :mongodb://localhost:27017
$db = $m->lxwdb; // Select database
//$db->createCollection('runtest'); // Create set
$collection=$db->runtest; // Select collection
$document=array(
"title" => "MongoDB",
"description" => "database",
"likes" => 100,
"url" => "http://www.runoob.com/mongodb/",
"by", " Novice tutorial "
);
// Inserted into the document
$res=$collection->insert($document);
echo ' Data insertion successful ';
// Query the document
$result=$collection->find();
foreach ($result as $res){
d($res['title']);
}
// Update the document
$collection->update(array("title"=>"MongoDB-11"),array('$set'=>array("title"=>"MongoDB-112")),array('multiple'=>true));
$result=$collection->findOne();
foreach ($result as $res){
d($res);
}
// Delete the document
$res=$collection->remove(array('0'=>false),array('justOne'=>false));
$res=$collection->remove(array('title'=>'MongoDB course '),array('justOne'=>true));
function d($data, $label='')
{
$ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
if(!$ajax) echo '<pre style="text-align: left;">';
if($label) echo $label.'--------------------------<br/>';
print_r($data);
if(!$ajax) echo '</pre>';
}Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/111436.html Link to the original text :https://javaforall.cn
边栏推荐
- This ten-year content industry infrastructure company is actually an invisible Web3 pioneer
- activemq--可持久化机制之AMQ
- 神经网络学习(1)前言介绍
- The operation cannot be completed because a folder or file in it is already open in another program
- 通过robocopy对文件/夹进行复制
- How to use pixi.js to make simple Parkour games
- Sort out Huawei ap-3010dn_ V2 configuration create WiFi
- Disable module (attribute node) in LabVIEW
- Detailed explanation of pipeline pipeline mechanism in redis
- Live broadcast preview | how to build an enterprise cloud management platform in the cloudy era?
猜你喜欢
![[machine learning] Finally, the important steps of machine learning modeling have been clarified](/img/75/07767ed694502f0c910d35e1447499.jpg)
[machine learning] Finally, the important steps of machine learning modeling have been clarified

The garbage classification data set used in the excellent Yolo target detection training is shared - about 3000 labeled

保姆级Scanner类使用详解

Do you know these methods of MySQL database optimization?

activemq--消息重试机制

Probe into Druid query timeout configuration → who is the querytimeout of datasource and jdbctemplate effective?

What are the commands used by pl/sql tools to export SQL files?

Common tool classes under JUC package

API健康状态自检

The simplest sklearn environment configuration tutorial in the whole network (100% success)
随机推荐
Redis sentry, master-slave deployment details
深入理解static关键字
Comparison between symmetric encryption and asymmetric encryption
BigDecimal 对数据进行四舍五入
整理 华为AP-3010DN_V2配置创建wifi
A picture to quickly understand envoyfilter in istio
@Scheduled源码解析
ActiveMQ -- leveldb of persistence mechanism
The simplest sklearn environment configuration tutorial in the whole network (100% success)
[common tools] obtain system status information based on psutil and gputil
C#语言和SQL Server数据库技术
c语言中的六个存储类型:auto register static extern const volatile
Feiling ok1028a core board adapts to rtl8192cu WiFi module
Silicon Valley classroom lesson 12 - official account on demand course and live broadcast management module
Arrange the array into the smallest number
idea 热部署
Rich text style word image processing
[NPM] the "NPM" item cannot be recognized as the name of cmdlets, functions, script files or runnable programs. Please check the spelling of the name. If the path is included, make sure the path is co
Write two channel (stereo) immediately Wav file
Troubleshooting error: NPM install emojis list failed