当前位置:网站首页>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
边栏推荐
- How to avoid duplicate data when the database is high and distributed
- activemq--消息重试机制
- Nacos搭建配置中心出现client error: invalid param. endpoint is blank
- Guangzhou has carried out in-depth "100 day action" to check the safety of self built commercial houses, and more than 2 million houses have been checked in two months
- 『怎么用』装饰者模式
- Druid 查询超时配置的探究 → DataSource 和 JdbcTemplate 的 queryTimeout 到底谁生效?
- 神经网络学习(1)前言介绍
- Leetcode-238. product of arrays other than itself
- Neural network learning (1) Introduction
- Sort out Huawei ap-3010dn_ V2 configuration create WiFi
猜你喜欢

JMeter test plan cannot be saved solution

Disable module (attribute node) in LabVIEW

Unity ugui interaction (new ideas)

分享一个避免递归的部门设计方法

activemq--死信队列

Ten thousand words long, one word thoroughly! Finally, someone has made business intelligence (BI) clear

ActiveMQ -- dead letter queue

Silicon Valley class lesson 11 - official account news and wechat authorization

SQL injection
![[stl]list Simulation Implementation](/img/92/2a78382700c1ebf299c6505d962c9c.png)
[stl]list Simulation Implementation
随机推荐
[deep learning] mask Dino Trilogy - the correct way to open Detr Pandora's box
[STL]list模拟实现
ActiveMQ -- JDBC code of persistent mechanism
[buuctf-n1book][Chapter 2 advanced web]ssrf training
idea中将lib目录下的jar包加入到项目中
Leetcode组合总和+剪枝
Write two channel (stereo) immediately Wav file
NFT guide for musicians
ActiveMQ -- leveldb of persistence mechanism
Activemq-- delayed delivery and scheduled delivery
OmniPeek packet capturing tool
『怎么用』装饰者模式
PHP date() function does not support processing numbers greater than 2147483648? "Suggested collection"
How to avoid duplicate data when the database is high and distributed
C#语言和SQL Server数据库技术
redis的五种数据结构原理分析
Activemq-- asynchronous delivery
Rich text style word image processing
ActiveMQ -- dead letter queue
有误差的字符串型时间比较方法String.compareTo