First acquainted with Mongdb data query articles (2)

table of Contents

Advanced query

Fuzzy query (regular expression)

Advanced modification

Specify field modification

Specify field query

Array operations

Specify field modification (array type)

Delete the first element of the array

Append an element to the end

Insert an element into the specified position of the array

Delete specific elements in the array

Batch operation of documents

Update multiple documents

Delete multiple documents

Operate non-existent documents

One word per text


Advanced query

Fuzzy query (regular expression)

$ Match the end position of the input string. If the Multiline property of the RegExp object is set, $ also matches'\n' or'\r'. To match the $ character itself, use \$.
( ) Mark the beginning and end of a sub-expression. The sub-expression can be retrieved for later use. To match these characters, use \( and \).
* Matches the preceding sub-expression zero or more times. To match * characters, use \*.
+ Match the preceding sub-expression one or more times. To match the + character, use \+.
. Matches any single character except the newline character \n. To match., use \..
[ Mark the beginning of a bracket expression. To match [, use \[.
? Match the preceding subexpression zero or one time, or specify a non-greedy qualifier. To match the? Character, use \?.
\ Mark the next character as either a special character, or a literal character, or a backward quote, or an octal escape character. For example,'n' matches the character'n'. '\n' matches a newline character. The sequence'\\' matches "\", while'\(' matches "(".
^ Match the starting position of the input string, unless used in a square bracket expression. When the symbol is used in a square bracket expression, it means that the set of characters in the square bracket expression is not accepted. To match the ^ character itself, use \^.
{ Mark the beginning of the qualifier expression. To match {, use \{.

 

We also have fuzzy queries in MySQL, but fuzzy queries in mongdb should be more practical than MySQL, because mongdb stores mostly document types, while MySQL is mostly data types.

MySQL syntax:

Find the records where there are both "three" and "cat" in u_name

SELECT * FROM [user] WHERE u_name LIKE '%三%' AND u_name LIKE '%猫%' 

mongdb syntax:

Find out Lei Wuxuan's information

db.students.find({name:/^雷.*轩$/})

Advanced modification

Specify field modification

In a table structure, we need to modify a certain field to ensure the real-time accuracy of the data. We need to make some modifications. However, as we said before, the modification can be modified with coverage, but we don't want this.

Case 1: For example, we encountered a scenario: when a physical education teacher was collecting information for the entire class, he found that the height measurement instrument seemed to be broken after the collection was completed, which caused the height of the class to decrease by 1cm. As a teacher What should you do for your physical education class?

//构造查询文档
use cqust;
var query = {
    major: '大数据',
    class: 1,
    grade: 2019,
    height: {
        $lt: 170
    }
};

After that, we can use loops, and loops can also be written in mongdb, but the grammar rules must meet the JavaScript grammar, otherwise an error will

Query after sorting

db.students.find(query).sort({height:-1});

We found that the query structure has the type of array structure, then we are wondering whether we can use array syntax to display

var restult1 = db.students.find(query);

restult1[0]["name"]

Write a query using JavaScript syntax

var idlist = new Array();

for (var i = 0; i < restult1.length(); i++) {
    idlist[i] = restult1[i]["name"];
}
idlist;

Now we can manipulate our problem

//更新操作文档

var querys={name:{$in:idlist}}

var updates={$inc:{height:-1}};

var options={multi:1};

db.students.update(querys, updates, options);

db.students.find(query).sort({height:-1});

The above question is modified based on a certain first field, so sometimes we modify the fields in the embedded document. At this time, how should we do batch operations: For example, I need to modify the grades of a certain subject in the course grades , Add a few points to it, then how should we locate this label field at this time, and then realize batch modification.

If you don’t think about it, you won’t be able to learn, and if you don’t think about it, you will lose it. You can leave it to yourselves. If you have an idea, you can leave a message in the comment area. Welcome your visit!

Specify field query

In a document, we need to get the score of a certain subject, and only request to return the information of this score

For example, we need to inquire, there is a subject called: Distributed *** information that failed the subject, what should we do

//查询分布式的课程的不及格信息,注意只需要返回该课程的分数
var 查询条件 = {
    'courses': {
        $elemMatch: {
            'course': /分布式/,
            'score': {
                $lt: 60
            }
        }
    }
}
var 返回条件2 = {
    _id: 0,
    'name': 1,
    'sno': 1,
    'courses': {$elemMatch:{'course':/分布式/}}   //利用数组elemMatch方法
};
db.students.find(查询条件, 返回条件2);

 

 When encountering a query in an array, we should first think of this operator: $elemMatch: {some parallel constraints}, for example, we need to query the score of a certain subject, and the score must be within the scope of a specific constraint. Then we need this method to satisfy the parallel relationship

Array operations

Specify field modification (array type)

For example, we need to modify the student ID: the height in the abody of the student of 2019000000 is 174,

// 先查询出数组元素的值
var 查询条件 = {'sno':2019000000}
var 返回条件 = {_id:0,'abody':1}
var res = db.students.findOne(查询条件,返回条件)
res.abody[0]=174
var 更新操作 = {$set:{'abody':res.abody}}
db.students.update(查询条件,更新操作)  //updateOne updateMany

We first use findone to return an array. If we use find() to operate directly, an error will be reported, which is obviously a limitation in the field array.

Delete the first element of the array

//删除数组的第一个元素
var 查询条件 = {'sno':2019000001}
var 更新操作={$pop:{'abody':-1}} //1代表删除最后一个
db.students.update(查询条件,更新操作)  

Here, the first element in abody is deleted. If we change the attribute in pop to 1, then it is the last one to be deleted. The actual scene is determined by ourselves.

Append an element to the end

//追加一个元素到末尾
var 查询条件 = {'sno':2019000001}
var 更新操作={$push:{'abody':65}}
db.students.update(查询条件,更新操作) 

Additional use of push command


Insert an element into the specified position of the array

//插入一个元素到数组的指定位置,把14插入abody的第一个元素里面
var 查询条件 = {'sno':2019000001}
var 更新操作={$push:{'abody':{$each:[14],$position:1}}}
db.students.update(查询条件,更新操作)  

The 1 index here is the middle position

Delete specific elements in the array

var 查询条件 = {'sno':2019000001}
var 更新操作={$pull:{'abody':164}}
db.students.update(查询条件,更新操作)  

Delete the specific element in abody, which is 164

After seeing so many operations on array types, do you remember the previous non-array fields? I talked about it before, let’s review it below:

//删除非数组里面的元素
var 查询条件 = {'sno':2019000001}
var 更新操作={$unset:{'body.weight':1}}
db.students.update(查询条件,更新操作)  

//增加非数组里面的字段元素
var 查询条件 = {'sno':2019000001}
var 更新操作={$unset:{'body.weight':1}}
db.students.update(查询条件,更新操作)  

Batch operation of documents

Update multiple documents

var 查询条件={'name':/^王/,gender:1}
db.students.find(查询条件)
var 更新操作={$inc:{'body.height':1}}
var 更新选项={multi:1}
//updatemany()更新多个文档,updateone()更新一个文档
db.students.update(查询条件, 更新操作, 更新选项)
db.students.find(查询条件)

Several documents have been updated, and the document information contains the conditions and constraints we need


Delete multiple documents

//默认删除全部的满足条件信息,deleteMany
var 查询条件={'name':/^王/,gender:1}
db.students.remove(查询条件)

//只删除第一个匹配结果
var 查询条件={'name':/^王/,gender:0}
var 删除选项={'justOne':1}  
db.students.remove(查询条件,删除选项)
//同理
db.students.deleteOne(查询条件)

Operate non-existent documents

Suppose we have a local document that doesn’t exist anymore, but we don’t know if this exists. At this time, we already have such a case locally. We need to query and update to upload this document record.

// 更新一个不存在的文档
var 王小王 = {
    "name": "王小王",
    "gender": 1,
    "body": {
        "height": 177,
        "weight": 60
    },
    "abody": [
        177,
        55
    ],
    "phone": "15730596577",
    "role": "student",
    "sno": 2019000891,
    "major": "大数据",
    "grade": 2019,
    "class": 3,
    "courses": [ ]
}
var 查询条件 = {"name": "王小王"} // 这个条件查询不到结果,数据库中没有这样的记录
var 替换文档 = 王小王
db.students.update(查询条件,替换文档)

 

var 更新选项 = {upsert:1}
db.students.update(查询条件,替换文档,更新选项)
/*
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("605738c72410a0e84779ac7d"),
	"writeConcernError" : [ ]
})
*/
db.students.find({_id:ObjectId("605738c72410a0e84779ac7d")})

Then we are assuming this case, for example, we sometimes accidentally write the wrong conditions, information that does not exist originally, will we make some restrictions on the operator to show some inserted information

var 查询条件 = {"name": "王小小"}  // 条件写错,查不到
var 更新操作 = {$set:{sno:2019999999}}  // 带操作符的更新文档
var 更新选项 = {upsert:1}
db.students.update(查询条件,更新操作,更新选项)
/*
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("6057395a2410a0e84779ac91"),
	"writeConcernError" : [ ]
})

*/
db.students.find({"_id" : ObjectId("6057395a2410a0e84779ac91")})
/* 新文档相当于在空白文档上做了更新
{
    "_id": ObjectId("6057395a2410a0e84779ac91"),
    "name": "王小小",
    "sno": 2019999999
}

*/

One word per text

  • When you are in a difficult situation, smiling openly is a kind of open-mindedness.
  • When someone is misunderstood, smiling slightly is a kind of accomplishment.
  • When you are wronged, smiling indifferently is a kind of generosity.
  • When helpless, Daguan smiled, which is a realm.
  • When being criticized, a calm smile is a kind of self-confidence.
  • When frustrated, I smiled happily, which is a kind of optimism.
  • Putting a smile on your face anytime, anywhere is also a kind of beauty.

Guess you like

Origin blog.csdn.net/weixin_47723732/article/details/114738455