How to realize where conditional filtering in MongoDB
In this issue, the editor will bring you about how to achieve where conditional filtering in MongoDB. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
In fact, when we are used to traditional relational database development, we may first think of the where clause, so we also provide "$where" in MongoDB.
Example: using where for data query
> db.emp.find ({"$where": "this.age > 40"}) .pretty ()
{
"_ id": ObjectId ("599108423268c8e84253be2c")
"name": "Zheng Qi"
"sex": "female"
"age": 50
"sal": 4700
"loc": "Chengdu"
Or:
> db.emp.find ("this.age > 40"). Pretty ()
{
"_ id": ObjectId ("599108423268c8e84253be2c")
"name": "Zheng Qi"
"sex": "female"
"age": 50
"sal": 4700
"loc": "Chengdu"
}
It can be simplified for "$where", but this kind of operation belongs to the judgment of each line of information, which is actually not convenient to use in the case of a large amount of data. In fact, the above code is strictly speaking a function that writes an operation.
> db.emp.find (function () {return this.age > 40;}) .pretty ()
{
"_ id": ObjectId ("599108423268c8e84253be2c")
"name": "Zheng Qi"
"sex": "female"
"age": 50
"sal": 4700
"loc": "Chengdu"
}
> db.emp.find ({"$where": function () {return this.age > 40;}}) .pretty ()
{
"_ id": ObjectId ("599108423268c8e84253be2c")
"name": "Zheng Qi"
"sex": "female"
"age": 50
"sal": 4700
"loc": "Chengdu"
}
The above is just a query for a judgment, and if you want to achieve multiple criteria, you need to use an and connection.
> db.emp.find ({"$and": [{"$where": "this.age > 20"}, {"$where": "this.age")