MongoDB operation basic command

MongoDB CRUD and full text index

Summary:
  1. How to add data
  2. Query of data
  3. Modification and deletion of data
  4. Full text index query

mongo shell is a js console that can perform js related operations, such as:

> 1+1
2
> var i=123;
> print(i)
123
>

Basic operation of database and collection

  #view the database
  show dbs;
  #Switch database
  use luban;
  #Create databases and sets, which are automatically created when inserting data
  db.friend.insertOne({name:"bryce",sex:"1"});
  #View collection
  show tables;
  show collections;
  #Delete collection
  db.friend.drop();
  #Delete database
  db.dropDatabase();
  1. How to add data

Description of Mongodb data insertion

  1. The new database does not need to design the model structure first, and it will be created automatically when inserting data.
  2. Different data field structures in the same set can be different

Insert related methods:

Insert single
db.friend.insertOne({name:"bryce",sex:"1"});
Insert multiple
db.friend.insertMany([
{name:"bryce",sex:"1"},{name:"jack",sex:"1",age:18,birthday:new Date("1996-11-02")}
]);
Specify ID
db.friend.insert([
		{_id:1,name:"bryce",sex:"1",age:1},
		{_id:2,name:"jack",sex:"2",birthday:new Date("1988-11-11")}
 ])

2. Query of data

Summary:

  1. Condition based basic query
  2. And, and, and, or, in, in, in, gt, gte, gte, gte, lt, $lte operators
  3. Sorting and paging based on sort skip limit method
  4. nested queries
  5. Array query
  6. Array nested query

Basic query:

ID based lookup
db.emp.find({_id:1101})
Attribute based lookup
db.emp.find({"name":"bryce"})
Operation and greater than operation
db.emp.find({"job":"IT","salary":{$gt:6000}})
in operation
db.emp.find({"job":{$in:["IT","teacher"]}})
or operation
db.emp.find({$or:[{job:"IT"},{job:"teacher"}] })

Sorting and paging:

sort skip limit

db.emp.find().sort({dep:1,salary:-1}).skip(5).limit(2)

Nested query:

When searching based on composite attributes, all their values must be included and in the order of one to two
db.student.find({grade:{redis:87,zookeper:85,dubbo:90} })
Find based on the specified value in the composite attribute. Note: the name must be in double quotation marks
db.student.find({"grade.redis":87});
db.student.find({"grade.redis":{"$gt":80}});

Array query:

Data insertion
db.subject.insertMany([
{_id:"001",name:"Zhang San",subjects:["redis","zookeper","dubbo"]},
{_id:"002",name:"Li Si",subjects:["redis","Java","mySql"]},
{_id:"003",name:"Wang Wu",subjects:["mySql","zookeper","bootstrap"]},
{_id:"004",name:"Zhao Liu",subjects:["Java","dubbo","Java"]},
])
As with nested queries, all values must be in the order of one to
db.subject.find({subjects:["redis","zookeper","dubbo"]})
$all matches the values of the two items in the array. Note: do not order
db.subject.find({subjects:{"$all": ["redis","zookeper"]}})
Simplify array query
db.subject.find({subjects:"redis"})
Simplify the array query and match any value in the array. Corresponding to $all
db.subject.find({subjects:{$in: ["redis","zookeper"]}})

Array nested query:

For basic query, you must query all, and the order is from one to two
db.subject2.find({subjects:{name:"redis",hour:12} })
The first array of the specified query is greater than 12
db.subject2.find({"subjects.0.hour":{$gt:12}})
Query any subject class time greater than 12
db.subject2.find({"subjects.hour":{$gt:12}})
The $elemMatch element matches, and the specified attribute is satisfied, and the order from one to is not required
db.subject2.find({subjects:{$elemMatch:{name:"redis",hour:12}}})
Any element matching in the array is not limited to the same object
db.subject2.find({"subjects.name":"mysql","subjects.hour":120})

Using cursor to traverse query data

var persons = db.persons.find();
    while(persons.hasNext()){
        obj = persons.next();
        print(obj.name) 
    }

Cursor several destruction conditions
1). The client sent him a message to destroy it
2). Cursor iteration completed
3). The default cursor will not be cleared even if it is useless for more than 10 minutes

Advanced Query options

1)$query 
2)$orderby
3)$maxsan: integer Maximum number of documents scanned
4)$min: doc Query start 
5)$max: doc End of query
6)$hint: doc Which index to use
7)$explain:boolean Statistics
8)$snapshot:boolean Consistent snapshot
Location index query

1. The nearest 3 points of query point (70180)

db.map.find({gis:{$near:[70,180]}},{_id:0,gis:1}).limit(3)

2. Query all points in a square with points (50,50) and points (190190) as diagonals

db.map.find({gis:{$within:{$box:[[50,50],[190,190]]}}},{_id:0,gis:1})

3. Find out the points in the center area under the rule that the center of the circle is (56,80) and the radius is 50

db.map.find({gis:{$with:{$center:[[56,80],50]}}},{_id:0,gis:1})
Count+Distinct+Group

1. count query results

db.persons.find({country:"USA"}).count()

2. Distinct de duplication
Please find out how many countries are there in people and what are they

# Key indicates the key to remove the duplicate 
db.runCommand({distinct:"persons",key:"country"}).values

3. group grouping

db.runCommand({ group:{
    ns:"The name of the collection",
    key:"Group key object", 
    initial:"Initialize accumulator",
    $reduce:"Resolver",
    condition:"condition",
    finalize:"Group completer" 
}})

First, the grouping will be carried out according to the key. Each document in each group will execute the $reduce method. It receives two parameters, one is the record in the group, and the other is the accumulator data
Please find out the information of the students with the best math scores in each country in persons (must be above 90)

db.runCommand({
    group:{
        ns:"persons",
        key:{"country":true},
        initial:{m:0},
        $reduce:function(doc,prev){
        if(doc.m>prev.m){ 
        prev.m = doc.m; 
        prev.name = doc.m;
        prev.country = doc.country;
        } },
        condition:{m:{$gt:90}}, 
        finalize:function(prev){ 
            prev.m = prev.name+" comes from "+prev.country+" ,Math score is "+prev.m; 
        }} 
})

Other queries

Query server version number and host operating system
db.runCommand({buildInfo:1})
Query execution set details, size, space, index, etc
db.runCommand({collStats:"persons"})
View the last error message of this operation set
db.runCommand({getLastError:"persons"})

Fixed set

characteristic
    Fixed sets have no index by default_id There is no index
    Since there is no need to allocate new space, his insertion speed is very fast
    The order of fixed sets is determined, resulting in very fast query speed
    The most suitable is log management
Create fixed collection
Creating a new fixed set requires a size of 100 bytes and can store 10 documents
db.createCollection("mycoll",{size:100,capped:true,max:10})
Convert an ordinary set into a fixed set
db.runCommand({convertToCapped:"persons",size:1000})
Sort fixed sets in reverse. By default, the order of insertion is sorted
db.mycoll.find().sort({$natural:-1})

3. Modification and deletion of data

modify
Set value
If the third parameter is true, the insertOrUpdate operation will be executed. If it is found, it will be updated. If it is not found, it will be inserted,
db.emp.update({_id:1101} ,{ $set:{salary:10300},true })
Self increasing
db.emp.update({_id:1101} ,{ $inc:{salary:200}})
$unset: delete specified key
db.emp.update({_id:1101},{$unset:{age:1}})
$push: array key operation:
1. If the specified array exists, add a value to it; 2. If the specified array does not exist, create an array key and add a value; 3. If the specified key is not of array type, an error will be reported;
The original document is:{ "_id" : ObjectId("5c6e02f6f578476166df7db3"), "name" : "bryce" }
#Execute statement
db.emp.update({"name":"bryce"},{"$push": {"score":{"$each":[ {math:90},
{art:80} ] } } } );
#Document becomes
{ "_id" : ObjectId("5c6e02f6f578476166df7db3"), "name" : "bryce", "score" : [ { "math" : 90 }, { "art" : 80 } ] }
$addToSet: when there is this value in the specified array, it is not inserted. On the contrary, the inserted classes are the array name
db.emp.update({name:"zhangsan"},{$addToSet:{classes:"English"}}) ;
$pop: delete the value of the specified array. When value=1, delete the last value, and when value=-1, delete the first value
db.emp.update({name:"zhangsan"},{$pop:{classes:1}})
$pull: deletes the value specified in the specified array
#$pullAll Batch delete specified array
db.emp.update({name:"zhangsan"},{$pull:{classes:"Chinese"}})
#If there are more than one in the array Chinese,Delete all
db.emp.update({name:"zhangsan"},{$pull:{classes:["Chinese"]}})
$: when modifying the specified array, if the array has multiple objects, but you only want to modify some of them, you need a locator:
db.emp.update({"classes.type":"AA"},{$set:{"classes.$.sex":"male "}})
Only the first item will be updated
db.emp.update({"dep":"Sales Department"},{$inc:{salary:100}})
Update all matching criteria
db.emp.updateMany({"dep":"Sales Department"},{$inc:{salary:100}})

Delete:

// Find based deletion
db.emp.deleteOne({_id:1101})
// Delete entire collection
db.project.drop()
// Delete Library
db.dropDatabase()

MongoDB index

1.1 index creation
db.books.ensureIndex{{number:1}}

Create the index and specify the name of the index

db.books.ensureIndex({number:1},{name:"book_"})

1.2 points needing attention in index use

1) When creating an index, note that 1 is creating an index in positive order - 1 is creating an index in reverse order
2) The creation of an index will improve the query performance and affect the insertion performance at the same time. For documents that often query and insert less, you can consider using an index
3) If you meet the index, you should pay attention to the order of the index
4) Indexing every key does not necessarily improve performance. Indexing is not everything
5) When sorting, if it is a large amount of data, you can also consider adding an index to improve the sorting performance

1.3 unique index

Solve the problem that the document books cannot insert duplicate values

1.4 eliminate duplicate values
#Insert the same name The value will report an error
db.books.ensureIndex({name:-1},{unique:true})

4. Full text index

Index creation

db.project.createIndex({name:"text",description:"text"})

Query based on index word segmentation

db.project.find({$text:{$search:"java jquery"}})

Index based phrase

db.project.find({$text:{$search:"\"Apache ZooKeeper\""}})

Filter specified words

db.project.find({$text:{$search:"java apache -Ali"}})

View execution plan

db.project.find({$text:{$search:"java -Ali"}}).explain("executionStats")

MongoDB aggregation operation

findAndModify: 
{
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
}

Tags: MongoDB

Posted by moselkady on Tue, 17 May 2022 15:57:36 +0300