当前位置:网站首页>Mongodb quick start
Mongodb quick start
2022-07-28 06:44:00 【yfyh2021】
install
1. Get installation package
wget https://fastdl.mongodb.org/linux/m2ongodb-linux-x86_64-rhel70-4.4.2.tgz
2. unpack
tar -xvzf mongodb-linux-x86_64-rhel70-4.4.2.tgz
3. Add to system execution path ( ~/.bashrc)
export PATH=$PATH:< You're a machine MongoDB bin Catalog , Such as :/usr/local/mongodb/mongodb-linux-x86_64-rhel70-4.4.2/bin>
perform source ~/.bashrc, Make it effective
4. Create a data directory
mkdir -p /data/db # This path is MongoDB Default data storage path
5. start-up MongoDB service
mongod # If you don't want to use the default data directory, you can use add to --dbpath Parameter to specify the path
To start the foreground, you need to open another window to link , So we use background startup
a. Log directory must be created for background startup , stay db Create under folder logpath Folder storage directory
mkdir logpath
b. Create a log file output.out
touch output.out
c. Background start
mongod --fork --logpath /data/db/logpath/output.out
The following screen appears, and the startup is successful
Check the log

Add data
db. aggregate .insertOne() // Add a single document
db. aggregate .insertMany([{},{}]) // Batch add documents
db. aggregate .insert() // Add a single document
db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
{ item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
{ item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);The above operation returns a document containing a confirmation indicator and a document containing each successfully inserted document _id Array of
Query data
Entire document query
db.inventory.find({}) Query all documents
db.inventory.find({}).pretty() Returns the formatted document
Conditions of the query
1. Accurate equivalent query
db.inventory.find( { status: "D" } );
db.inventory.find( { qty: 0 } );
2. Multiconditional query
db.inventory.find( { qty: 0, status: "D" } );
3. Nested object precise query
db.inventory.find( { "size.uom": "in" } );
4. Return the specified field
db.inventory.find( { }, { item: 1, status: 1 } );
Default will return _id Field , You can also specify _id:0 , No return _id Field
5. Conditions of the query and
db.inventory.find({$and:[{"qty":0},{"status":"A"}]}).pretty();
6. Conditions of the query or
db.inventory.find({$or:[{"qty":0},{"status":"A"}]}).pretty();
Mongo Query conditions and SQL Query cross reference table
SQL | MQL |
a<>1 perhaps a!=1 | { a : {$ne: 1}} |
a>1 | { a: {$gt:1}} |
a>=1 | { a: {$gte:1}} |
a<1 | { a: {$lt:1}} |
a<=1 | { a: { $lte:1}} |
in | { a: { $in:[ x, y, z]}} |
not in | { a: { $nin:[ x, y, z]}} |
a is null | { a: { $exists: false }} |
Composite primary key
db.demeDoc.insert(
{
_id: { product_name: 1, product_type: 2},
supplierId:" 001",
create_Time: new Date()
}
)_id Adding multiple fields to is a composite primary key . Composite primary keys are sequential .
Logical operators match
$not : Documents that do not match the filter criteria
$and : Match documents that meet multiple filter criteria at the same time
$or : Match the document with at least one filter condition
$nor : Match documents that do not meet multiple filter criteria 1.$not
{ field: { $not : { operator-expression} }}
db.members.find({points: { $not: { $lt: 100}}} );2.$and
{ $and : [ condition expression1 , condition expression2 ..... ]}
Nickname equals Cao Cao , The integral is greater than 1000 Documents
db.members.find({$and : [ {nickName:{ $eq : " Cao Cao "}}, {points:{ $gt:1000}}]});When acting on different fields It can be omitted $and
db.members.find({nickName:{ $eq : " Cao Cao "}, points:{ $gt:1000}});When acting on the same field, it can be simplified to
db.members.find({points:{ $gte:1000, $lte:2000}});3.$or
{ $or :{ condition1, condition2, condition3,... }}
db.members.find(
{$or : [
{nickName:{ $eq : " Liu bei "}},
{points:{ $gt:1000}}]}
);
Document projection : Can selectively return data
db.collection.find( Query criteria , Projection settings )
1 Identification returns ,0 Identification does not return , Non primary key fields cannot be mixed 0 or 1
db.members.find({},{_id:0 ,nickName:1, points:1})
db.members.find({},{_id:0 ,nickName:1, points:0})
$slice Return some elements in the array
Insert a piece of data
db.members.insertOne(
{
_id: {uid:3,accountType: "qq"},
nickName:" Zhang Fei ",
points:1200,
address:[
{address:"xxx",post_no:0000},
{address:"yyyyy",post_no:0002}
]}
);Returns the first element of the array
db.members.find(
{},
{_id:0,
nickName:1,
points:1,
address:
{$slice:1}
});
slice: value
1: The first element of the array
-1: The last element
-2: The last two elements
slice[ 1,2 ] : skip, limit Corresponding relationship
elementMatch Match array elements
Add a set of data
db.members.insertOne(
{
_id: {uid:4,accountType: "qq"},
nickName:" Zhang San ",
points:1200,
tag:["student","00","IT"]}
);Inquire about tag The first match in the array "00" The elements of
db.members.find(
{},
{_id:0,
nickName:1,
points:1,
tag: { $elemMatch: {$eq: "00" } }
});update operation
updateOne/updateMany Method requires that the update condition section must have one of the following , Otherwise, an error will be reported
$set Add a new field to the qualified document , If there is this field, modify its value
$unset Give qualified documents , Delete a field
$push: Add an object to the bottom of the array
$pop: Delete an object from the bottom of the array
$pull: If it matches the specified value , Delete the corresponding object from the array
$pullAll: If you match any value , Delete the corresponding object from the data
$addToSet: If it doesn't exist, add a value to the array
update operation
db.collection.update( <query>,<update>,<options>)
<query> Defines the filter criteria when updating
<update> The document provides updates
<options> Declared some parameters of the update operation
Insert two data demonstrations :
db.userInfo.insert([
{ name:"zhansan",
tag:["90","Programmer","PhotoGrapher"]
},
{ name:"lisi",
tag:["90","Accountant","PhotoGrapher"]
}]);take tag There is 90 Documents , Add a field : flag: 1
db.userInfo.updateMany(
{tag:"90"},
{$set:{flag:1}}
);flag The field now has , In update, it is an update operation
db.userInfo.updateOne(
{tag:"90"},
{$set:{flag:2}}
);
By default, only the first matching value will be updated , Can be set by options {multi: true} Set to match multiple documents and update
db.doc.update(
{name:"zhangsan"},
{$set:{ flag: 1 }},
{multi:true}
);Update Operators
$set Update or add fields
$unset Delete field
$rename Rename field
$inc Add and subtract field values
$mul Multiply field values
$min Use the minimum value
$max Maximum value for one time use
Delete
db.collection.remove(<query>,<options>)
By default , All documents that meet the criteria will be deleted , Parameters can be set { justOne:true}, Only the first document that meets the requirements of addition will be deleted
db.collection.drop( { writeConcern:<doc>})
<doc> Defines the security write level of this delete collection operation
db.collection.remove Only all documents will be deleted , Use it directly remve Deleting all documents is inefficient , have access to drop Delete the collection , Just recreate the collection and index .
边栏推荐
- Project compilation nosuch*** error problem
- OJ 1020 最小的回文数
- NIO示例
- Leetcode 刷题日记 剑指 Offer II 055. 二叉搜索树迭代器
- Redhawk Dynamic Analysis
- Leetcode brush question diary sword finger offer II 053. Medium order successor in binary search tree
- 空气传导耳机哪个牌子好、备受好评的气传导耳机推荐
- [dynamic planning -- the best period series for buying and selling stocks]
- Water bottle effect production
- OJ 1129 fraction matrix
猜你喜欢
随机推荐
2022年七夕礼物推荐!好看便宜又实用的礼物推荐
RayMarching实现体积光渲染
OJ 1131 美丽数
气传导蓝牙耳机哪个好、气传导蓝牙耳机排行榜
ZOJ Problem 1005 jugs
OJ 1020 最小的回文数
七夕送女朋友什么礼物好?不会送礼的男生速看!
Leetcode brush question diary sword finger offer II 048. serialization and deserialization binary tree
New Selenium
OJ 1045 反转然后相加
[dynamic planning -- the best period series for buying and selling stocks]
RayMarching realizes volume light rendering
动态规划--简单题型之爬楼梯
What's a gift for girls on Chinese Valentine's day? Selfie online and thoughtful gift recommendation
开放式耳机有哪些、四款音质超好的气传导耳机推荐
Pyppeter drop-down selenium drop-down
Project compilation nosuch*** error problem
[PTA----树的遍历]
What are the open earphones? Four types of air conduction earphones with excellent sound quality are recommended
Graphic pipeline foundation (II)

![[pta-- use queues to solve the problem of monkeys choosing kings]](/img/54/94359fb3557ac07f7786ecf61a5409.png)







