Common MongoDB query syntax

A query

find method

db.collection_name.find(); 

Search results: 

select * from users;

db.users.find();

 

Specify a return those columns (key): 

select name, skills from users;

db.users.find({}, {'name' : 1, 'skills' : 1}); 

Supplementary Description: The first place where {} {} The second condition specifies that the display and non-display column (0 means no display 1 shows a display)

 

where conditions: 

1. Simple is equal to: 

select name, age, skills from users where name = 'hurry'; 

db.users.find({'name' : 'hurry'},{'name' : 1, 'age' : 1, 'skills' : 1});

 

2. Use and 

select name, age, skills from users where name = 'hurry' and age = 18; 

db.users.find({'name' : 'hurry', 'age' : 18},{'name' : 1, 'age' : 1, 'skills' : 1});

 

3. Use or 

select name, age, skills from users where name = 'hurry' or age = 18; 

db.users.find({ '$or' : [{'name' : 'hurry'}, {'age' : 18}] },{'name' : 1, 'age' : 1, 'skills' : 1});

 

4.<, <=, >, >= ($lt, $lte, $gt, $gte ) 

select * from users where age >= 20 and age <= 30; 

db.users.find({'age' : {'$gte' : 20, '$lte' : 30}});

 

5.使用in, not in ($in, $nin) 

select * from users where age in (10, 22, 26); 

db.users.find({'age' : {'$in' : [10, 22, 26]}});

 

6. Matching null 

select * from users where age is null; 

db.users.find({'age' : null);

 

7.like (mongoDB supports regular expressions) 

select * from users where name like "%hurry%"; 

db.users.find({name:/hurry/}); 

 

select * from users where name like "hurry%"; 

db.users.find({name:/^hurry/}); 

 

8. Use of the distinct 

select distinct (name) from users; 

db.users.distinct('name');

 

9. Use count 

select count(*) from users; 

db.users.count(); 

 

10. The array of query (mongoDB own unique) 

If skills are [ 'java', 'python'] 

db.users.find ({ 'skills': 'java'}); the statement can be successfully matched 

 

$all 

db.users.find ({ 'skills': { '$ all': [ 'java', 'python']}}) skills and must contain both java python 

 

$size 

db.users.find ({ 'skills': { '$ size': 2}}) $ size unfortunately can not be used in combination with other lt $

 

$slice 

db.users.find({'skills' : {'$slice : [1,1]}}) 

Two parameters are the number of offset and return

 

11. queries embedded documents  

12. Powerful $ where query

db.foo.find();                   

{ "_id" : ObjectId("4e17ce0ac39f1afe0ba78ce4"), "a" : 1, "b" : 3, "c" : 10 }

{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 } 

If you want to query b = c document how to do? 

> db.foo.find({"$where":function(){

    for(var current in this){

        for(var other in this){

            if(current != other && this[current] == this[other]){

                return true;    

            }

        }

    }

    return false; 

}}); 

 

{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 } 

 

1). Greater than, less than, greater than, or equal to, less than or equal

$ Gt: greater than

$ Lt: less than

$ Gte: greater than or equal to

$ Lte: less than or equal to

example:

db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value

db.collection.find({ "field" : { $lt: value } } ); // less than : field < value

db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value

db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value

 

The query j is greater than 3, less than 4: 

db.things.find({j : {$lt: 3}});

db.things.find({j : {$gte: 4}}); 

It can also be combined in a single statement: 

db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value

 

2) does not equal $ ne 

example: 

db.things.find( { x : { $ne : 3 } } ); 

 

3) in 和 not in ($in $nin)

grammar:

db.collection.find( { "field" : { $in : array } } ); 

example:

db.things.find({j:{$in: [2,4,6]}});

db.things.find({j:{$nin: [2,4,6]}});

 

4) a modulo operation $ mod

The following operations:

db.things.find( "this.a % 10 == 1") 

It can be used instead of $ mod:

db.things.find( { a : { $mod : [ 10 , 1 ] } } )

 

5)  $all

And $ in $ all similar, but he needs to match all the values ​​in the conditions:

If an object:

{ a: [ 1, 2, 3 ] } 

The following conditions can match: 

db.things.find( { a: { $all: [ 2, 3 ] } } ); 

But would not the following conditions: 

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );

 

6)  $size

$ Size matching the number of elements in the array, if an object: {a: [ "foo"]}, he has only one element:

The following statement can match:

db.things.find( { a : { $size: 1 } } ); 

The official line that can not be used to match elements within a range of, if looking for $ size <5 and the like, they suggested creating a field to hold the number of elements. 

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

  

7)$exists 

$ Exists for determining if an element is present: 

Such as: 

db.things.find ({a: {$ exists: true}}); // if a element exists, returns

db.things.find ({a: {$ exists: false}}); // if the element a is not present, returns

 

8)  $type 

$ Type to match the type of an element based bson type, such as to match according to the type of ID 

Type and ID corresponding list is as follows:

http://www.w3cschool.cc/mongodb/mongodb-operators-type.html

Changing field types are as follows:

http://loo2k.com/blog/mongodb-change-field-type/

http://blog.chinaunix.net/uid-15795819-id-3873422.html

Java comparison type and type as follows:

http://docs.mongodb.org/ecosystem/drivers/java-types/

http://docs.mongodb.org/manual/reference/bson-types/ 

db.things.find( { a : { $type : 2 } } ); // matches if a is a string

db.things.find( { a : { $type : 16 } } ); // matches if a is an int 

 

9) regular expressions

mongo support for regular expressions, such as:

db.customers.find ({name: /acme.*corp/i}); // meaning behind i is case-sensitive 

 

10) value in the query data

The following query is a query in the record red colors, if the colors are elements of a data, the database will traverse the elements of the array to query.

db.things.find( { colors : "red" } ); 

 

11) $ elemMatch

If the object has an element of an array, then $ elemMatch can match elements within the array within:

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 

{ "_id" : ObjectId("4b5783300334000000000aa9"), 

"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]

$ ElemMatch: {a: 1, b: {$ gt: 1}} must match all of the conditions on the job. 

Note that the above statement and the following is not the same. 

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } ) 

$ ElemMatch match { "a": 1, "b": 3}, while the back is a match { "b": 99}, { "a": 11} 

 

12) the value of the embedded object query

db.postings.find( { "author.name" : "joe" } ); 

Note that usage is author.name, with a point on the line. A more detailed look at the possible links: dot notation 

for example: 

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}}) 

If we want to query authors name is Jane, we can: 

> db.blog.findOne({"author.name" : "Jane"}) 

If you do not point it would need to match with the following sentence: 

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}}) 

The following sentence: 

db.blog.findOne({"author" : {"name" : "Jane"}}) 

It can not be matched, because mongodb for sub-objects, he is an exact match. 

 

13) unary operator $ not negated

Such as: 

db.customers.find( { name : { $not : /acme.*corp/i } } ); 

db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } ); 

mongodb There are many functions can be used, such as sorting and statistics, please refer to the original. 

There is no or mongodb (or) operator, instead of only using alternative approach, refer to the following links: 

http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions

Category: MongoDB 

 

Second, update

mongodb update There are two commands:

1) .update () command

db.collection.update( criteria, objNew, upsert, multi ) 

criteria: update query criteria, within a similar sql update query where the back

objNew: update objects and some of the newer operators (e.g., $, $ inc is ...) and the like, may be understood as a set behind the sql update query

upsert: This parameter mean, if there is no record update, whether to insert objNew, true inserted, the default is false, not inserted.

multi: mongodb default is false, only updating the first record found, if this parameter is true, according to the conditions put many records to check out all the updates. 

Example:

db.test0.update ({ "count": {$ gt: 1}}, {$ set: { "test2": "OK"}}); first record updated only

db.test0.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true ); 全更新了

db.test0.update ({ "count": {$ gt: 4}}, {$ set: { "test5": "OK"}}, true, false); first added to the list only

db.test0.update ({ "count": {$ gt: 5}}, {$ set: { "test5": "OK"}}, true, true); whole added to the list

db.test0.update ({ "count": {$ gt: 15}}, {$ inc: { "count": 1}}, false, true); Updated Full

db.test0.update ({ "count": {$ gt: 10}}, {$ inc: { "count": 1}}, false, false); update only the first

 

2) .save () command 

db.collection.save( x ) 

x is to update the object, only a single record. 

If there has been one and the same target and x "_id" is recorded in the collection. x mongodb will replace the record collection objects already exist, or it will insert the object x, the _id if not, the system automatically generates a re-insertion x. The above corresponds to the update statement upsert = true, multi = false in the case.

Example:

db.test0.save ({count: 40, test1: "OK"}); #_id will be generated

db.test0.save ({_ id: 40, count: 40, test1: "OK"}); # if _id test0 40 is equal to the inside, replaced, or insertion. 

mongodb update operator:

1) $inc

Usage: {$ inc: {field: value}}

Means for increasing a field number field value, for example:

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 16, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 1 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 17, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 2 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 19, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $inc : { "count" : -1 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }

 

2) $set

Usage: {$ set: {field: value}}

It is the equivalent of sql set field = value, all data types are supported $ set. example:

> db.test0.update( { "_id" : 15 } , { $set : { "test1" : "testv1","test2" : "testv2","test3" : "testv3","test4" : "testv4" } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "testv1", "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }

 

3) $unset

Usage: {$ unset: {field: 1}}

As the name suggests, it is to delete the field. example:

> db.test0.update( { "_id" : 15 } , { $unset : { "test1":1 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $unset : { "test2": 0 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $unset : { "test3":asdfasf } } );

Fri May 14 16:17:38 JS Error: ReferenceError: asdfasf is not defined (shell):0

 

> db.test0.update( { "_id" : 15 } , { $unset : { "test3":"test" } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test4" : "testv4", "test5" : "OK" }

 

I did not see the field: 1 inside 1 is used to do, anyway, as long as there is something on the line.

 

4) $push

Usage: {$ push: {field: value}}

The value added to the field to go inside, it must be a field array type for the job, if the field does not exist, a new array type added. example:

 

> db.test0.update( { "_id" : 15 } , { $set : { "test1" : ["aaa","bbb"] } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb" ], "test4" : "testv4", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $push : { "test1": "ccc" } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test4" : "testv4", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $push : { "test2": "ccc" } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $push : { "test1": ["ddd","eee"] } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }5) $pushAll

 

 

5) $ Pushall

用法:{ $pushAll : { field : value_array } }

With $ push, but a plurality of values ​​may be added into an array field. example:

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $pushAll : { "test1": ["fff","ggg"] } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ], "fff", "ggg" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

 

6)  $addToSet

Usage: {$ addToSet: {field: value}}

Adding a value into the array, and only when this value is not within the array was increased. example:

> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18,  

  "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555"],  

  "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" 

 }

> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18,  

  "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555"], "test2" : [ "ccc" ],  

  "test4" : "testv4", "test5" : "OK" 

}

> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18,  

  "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ], 

  "test4" : "testv4", "test5" : "OK"  

}

> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ],  

  "test4" : "testv4", "test5" : "OK"  

}

 

7) $pop

To delete a value in an array

usage:

Delete the last value: {$ pop: {field: 1}} remove the first value: {$ pop: {field: -1}}

Note that only delete a value, that is to say with only 1 or -1, 2 or -2 without use to delete two. mongodb 1.1 and later can use, for example:

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

  "test1" : ["bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"],  

  "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"  

}

> db.test0.update( { "_id" : 15 } , { $pop : { "test1": -1 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

  "test1" : ["ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"],  

  "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" 

 }

> db.test0.update( { "_id" : 15 } , { $pop : { "test1": 1 } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18,  

  "test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",

  "test5" : "OK"  

}

 

8) $pull

Usage: $ pull: {field: value}}

To delete a field from an array of value equal value. example:

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",

"test5" : "OK" }

 

> db.test0.update( { "_id" : 15 } , { $pull : { "test1": "ggg" } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"

: "OK" }

 

9) $pullAll

用法:{ $pullAll : { field : value_array } }

With $ pull, multiple values ​​in the array can be deleted once. example:

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"

: "OK" }

 

> db.test0.update( { "_id" : 15 } , { $pullAll : { "test1": [ "ccc" , "fff" ] } } );

> db.test0.find( { "_id" : 15 } );

{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ [ "ddd", "eee" ], [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

 

 

10) $ operator

$ Is his own idea and, on behalf of the conditions identified by an array inside himself. Oh, Au comparison mouth. Look at the example of the official:

> t.find()

{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }

 

> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )

 

> t.find()

{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }

 

Note that, the first array entry $ apply only to find, behind on the matter. Or look at an example:

> t.find();

{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }

> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);

> t.find();

 

Also note that $ $ unset with the use of time, will leave a null array items, but you can use {$ pull: {x: null}} delete all null array of items. example:

> t.insert({x: [1,2,3,4,3,2,3,4]})

> t.find()

{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }

> t.update({x:3}, {$unset:{"x.$":1}})

> t.find()

{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }

 

{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] } 

 

============ array element operation example ================ 

> db.arraytest.insert({id:2, name:'leon', comments:[{id:'011', content:'cmt11'}, {id:'012', content:'cmt12'}, {id:'013', content:'cmt13'}]}) 

1. The elements within the array can direct inquiries 

> db.arraytest.find({'comments.id':'002'})

 

2. Update the value of a node in the array, with $ symbol 

db.arraytest.update({'comments.id':'012'}, {$set: {'comments.$.content':'cmtttt012'}})

 

3. To delete a column array, becomes null 

> db.arraytest.update({'comments.id':'012'}, {$unset: {'comments.$':1}})

 

 4. Adding an element to the array, if no element occurs before the new array 

> db.arraytest.update({'comments.id':'112'}, {$push: {'comments.$.reply': {'rid':'r21', content:'reply22'}}}) 

 

Transfer: https: //www.cnblogs.com/shenyixin/p/9453742.html

Guess you like

Origin www.cnblogs.com/hankyoon/p/11641310.html