MongoDB Common Statements

Source: Internet
Author: User
Tags findone mongodb update

First, query

Find method

Db.collection_name.find ();

Query all the results:

select * from Users;

Db.users.find ();

Specifies that those columns (keys) are returned:

Select name, skills from users;

Db.users.find ({}, {' name ': 1, ' Skills ': 1});

Supplemental Note: The first {} Put where condition the second {} Specifies that those columns are displayed and not displayed (0 means No 1 is displayed)

Where Condition:

1. Simple equals:

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

Db.users.find ({' name ': ' Hurry '},{' name ': 1, ' age ': 1, ' Skills ': 1});

2. Using and

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

Db.users.find ({' name ': ' Hurry ', ' age ': 18},{' name ': 1, ' age ': 1, ' Skills ': 1});

3. Use the OR

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

Db.users.find ({' $or ': [{' name ': ' Hurry '}, {' Age ': +}]},{' name ': 1, ' age ': 1, ' Skills ': 1});

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

SELECT * from the users where age >= and the age <= 30;

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

5. Using in, not in ($in, $nin)

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

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

6. Match NULL

SELECT * from the users where age is null;

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

7.like (MongoDB supports regular expressions)

SELECT * from the users where name like "%hurry%";

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

SELECT * from the users where name like "hurry%";

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

8. Using distinct

Select DISTINCT (name) from users;

Db.users.distinct (' name ');

9. Use the Count

Select COUNT (*) from users;

Db.users.count ();

10. Array query (MongoDB own special)

If skills is [' java ', ' Python ']

Db.users.find ({' Skills ': ' java '}); The statement can match the success

$all

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

$size

Db.users.find ({' skills ': {' $size ': 2}}) Unfortunately $size cannot be used in combination with $LT, etc.

$slice

Db.users.find ({' skills ': {' $slice: []}})

Two parameters are offset and return quantity, respectively

11. Querying Inline 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}

What if I want to query the document B = c?

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

For (Var-in-this) {

For (var with 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 to

$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

If query J is greater than 3, less than 4:

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

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

can also be combined within a single statement:

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

2) Not equal to $ne

Example:

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

3) in and 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) modulo Operation $mod

As in the following operation:

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

Available $mod instead of:

Db.things.find ({A: {$mod: [10, 1]}})

5) $all

$all is similar to $in, but he needs to match all the values in the condition:

If you have an object:

{A: [1, 2, 3]}

The following conditions can be matched:

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

But the following conditions are not:

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

6) $size

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

The following statements can be matched:

Db.things.find ({A: {$size: 1}});

The official web says it can't be used to match a range of elements, and if you're looking for $size<5, they recommend 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-a range, create an extra size field that is increment when you add elements.

7) $exists

$exists used to determine whether an element exists:

Such as:

Db.things.find ({A: {$exists: true}}); If element A is present, it returns

Db.things.find ({A: {$exists: false}}); If element A does not exist, it returns

8) $type

$type match the type of an element based on Bson type, as if it were matched by type ID

The types and IDs correspond to the following list:

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

Change the field type as follows:

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

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

Types and Java types are compared 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 supports regular expressions, such as:

Db.customers.find ({name:/acme.*corp/i}); The meaning of the latter I is case-sensitive

10) Querying values within the data

The following query is a record of red in query colors, and if the colors element is a data, the database will iterate over the elements of this array to query.

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

) $elemMatch

If an object has an element that is an array, then $elemmatch can match the elements within the array:

> T.find ({x: {$elemMatch: {a:1, B: {$gt: 1}}})

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

"X": [{"A": 1, "B": 3}, 7, {"B": [+]}, {"A": 11}]

}

$elemMatch: {a:1, B: {$gt: 1}} All conditions must match.

Note that the above statement is not the same as below.

> T.find ({"X.A": 1, "x.b": {$gt: 1}})

$elemMatch is the match {"A": 1, "B": 3}, and the following is the match {"B": "A", {"a": 11}

12) Querying the values of embedded objects

Db.postings.find ({"Author.name": "Joe"});

Note that usage is author.name, just use one point. More detailed can see this link: dot notation

As an example:

> Db.blog.save ({title: "My first Post", Author: {Name: "Jane", Id:1}})

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

> Db.blog.findOne ({"Author.name": "Jane"})

If not, then you need to use the following sentence to match:

Db.blog.findOne ({"Author": {"name": "Jane", "id": 1}})

The following sentence:

Db.blog.findOne ({"Author": {"name": "Jane"}})

is not matched, because MongoDB for sub-objects, he is exact match.

13) The meta-operator $not take the inverse

Such as:

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

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

MongoDB also has a lot of functions to use, such as sorting, statistics, etc., please refer to the original text.

MongoDB currently does not have or (or) operators, can only be replaced by a workaround, you may refer to the following links:

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

Category: MongoDB

Second, update

MongoDB Update has two commands:

1). Update () command

Db.collection.update (criteria, objnew, Upsert, Multi)

Criteria:update query conditions, similar to those in the SQL update query

Objnew:update objects and some updated operators (such as $, $inc ... ) can also be understood as the SQL update query within the set after the

Upsert: This parameter means that if there is no record of update, insert Objnew,true is inserted, default is False, not inserted.

Multi:mongodb default is False, only update the first record found, if this parameter is true, the condition is checked out all the records are updated.

Cases:

Db.test0.update ({"Count": {$gt: 1}}, {$set: {"test2": "OK"}}); Only the first record is updated

Db.test0.update ({"Count": {$gt: 3}}, {$set: {"test2": "OK"}},false,true); It's all updated.

Db.test0.update ({"Count": {$gt: 4}}, {$set: {"Test5": "OK"}},true,false); Only added the first one.

Db.test0.update ({"Count": {$gt: 5}}, {$set: {"Test5": "OK"}},true,true); All added in.

Db.test0.update ({"Count": {$gt: $}}, {$inc: {"Count": 1}},false,true), fully updated

Db.test0.update ({"Count": {$gt: Ten}}, {$inc: {"Count": 1}},false,false); Update only the first one

2). Save () command

Db.collection.save (x)

X is the object to be updated, only a single record.

If a record of the same "_id" as the X object already exists within the collection. MongoDB will replace the X object with the existing record in collection, otherwise the X object will be inserted, and if there is no _id within X, a re-insert will be generated automatically. Equivalent to the upsert=true,multi=false of the above UPDATE statement.

Cases:

Db.test0.save ({count:40,test1: "OK"}); #_id系统会生成

Db.test0.save ({_id:40,count:40,test1: "OK"}); #如果test0内有_id等于40的, will be replaced, otherwise inserted.

The update operator for MongoDB:

1) $inc

Usage: {$inc: {Field:value}}

Meaning to a Number field field adds value, for example:

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

{"_id": {"Floatapprox": +}, "Count": +, "test1": "Testtest", "test2": "OK", "test3": "Testtest", "test4": "OK" , "Test5": "OK"}

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

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

{"_id": {"Floatapprox": {"}", "Count": +, "test1": "Testtest", "test2": "OK", "test3": "Testtest", "test4": "OK" , "Test5": "OK"}

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

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

{"_id": {"Floatapprox":}, "Count": +, "test1": "Testtest", "test2": "OK", "test3": "Testtest", "test4": "OK" , "Test5": "OK"}

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

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

{"_id": {"Floatapprox": {"}", "Count": "Test1": "Testtest", "test2": "OK", "test3": "Testtest", "test4": "OK" , "Test5": "OK"}

2) $set

Usage: {$set: {Field:value}}

is the equivalent of SQL set field = value, all data types support $set. Cases:

> db.test0.update ({"_id":}, {$set: {"test1": "TESTV1", "test2": "Testv2", "test3": "TESTV3", "test4": "Test V4 "}});

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

{"_id": {"Floatapprox": "$", "Count": "Test1": "TESTV1", "test2": "Testv2", "test3": "TESTV3", "test4": "tes TV4 "," Test5 ":" OK "}

3) $unset

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

As the name implies, the field is deleted. Cases:

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

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

{"_id": {"Floatapprox": {"}", "Count":, "test2": "Testv2", "test3": "TESTV3", "test4": "TESTV4", "Test5": "OK" }

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

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

{"_id": {"Floatapprox": "$", "Count": "Test3": "TESTV3", "test4": "TESTV4", "Test5": "OK"}

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

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

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

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

{"_id": {"Floatapprox": +}, "Count": "Test4": "TESTV4", "Test5": "OK"}

Do not see field:1 inside of 1 is what to use, anyway as long as there is something on the line.

4) $push

Usage: {$push: {Field:value}}

Append value To field, field must be array type, if field does not exist, a new array type will be added. Cases:

> db.test0.update ({"_id":}, {$set: {"test1": ["AAA", "BBB"]}});

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

{"_id": {"Floatapprox": "$", "Count":, "test1": ["AAA", "BBB"], "test4": "TESTV4", "Test5": "OK"}

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

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

{"_id": {"Floatapprox": {"}", "Count":, "test1": ["AAA", "BBB", "CCC"], "test4": "TESTV4", "Test5": "OK"}

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

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

{"_id": {"Floatapprox": "$", "Count":, "test1": ["AAA", "BBB", "CCC"], "test2": ["CCC"], "test4": "TESTV4" , "Test5": "OK"}

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

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

{"_id": {"Floatapprox": "$", "count": +, "test1": ["AAA", "BBB", "CCC", ["ddd", "Eee"]], "test2": ["CCC"], "Test4": "TESTV4", "Test5": "OK"}5) $pushAll

5) $pushAll

Usage: {$pushAll: {Field:value_array}}

With $push, it is possible to append multiple values to an array field at a time. Cases:

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

{"_id": {"Floatapprox": "$", "count": +, "test1": ["AAA", "BBB", "CCC", ["ddd", "Eee"]], "test2": ["CCC"], "Test4": "TESTV4", "Test5": "OK"}

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

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

{"_id": {"Floatapprox": "$", "count": +, "test1": ["AAA", "BBB", "CCC", ["ddd", "Eee"], "fff", "GGG"], "test2" : ["CCC"], "test4": "TESTV4", "Test5": "OK"}

6) $addToSet

Usage: {$addToSet: {Field:value}}

Adds a value to the array, and only if the value is not inside the array. Cases:

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

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

{"_id": {"Floatapprox": "$", "count": 18,

"Test1": ["AAA", "BBB", "CCC", ["ddd", "Eee"], "fff", "GGG", ["111", "222"], "444", "555"],

"Test2": ["CCC"], "test4": "TESTV4", "Test5": "OK"

}

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

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

{"_id": {"Floatapprox": "$", "count": 18,

"Test1": ["AAA", "BBB", "CCC", ["ddd", "Eee"], "fff", "GGG", ["111", "222"], "444", "555"], "test2": ["CCC"],

"Test4": "TESTV4", "Test5": "OK"

}

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

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

{"_id": {"Floatapprox": "$", "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":}, {$addToSet: {"test1": ["444", "555"]}});

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

{"_id": {"Floatapprox": {"}", "Count": +, "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 within an array

Usage:

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

Note that only one value can be deleted, that is, only 1 or-1, not 2 or--and two are deleted. MongoDB 1.1 and later versions are only available, for example:

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

{"_id": {"Floatapprox": "$", "count": 18,

"Test1": ["BBB", "CCC", ["ddd", "Eee"], "fff", "GGG", ["111", "222"], "444"],

"Test2": ["CCC"], "test4": "TESTV4", "Test5": "OK"

}

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

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

{"_id": {"Floatapprox": "$", "count": 18,

"Test1": ["CCC", ["ddd", "Eee"], "fff", "GGG", ["111", "222"], "444"],

"Test2": ["CCC"], "test4": "TESTV4", "Test5": "OK"

}

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

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

{"_id": {"Floatapprox": "$", "count": 18,

"Test1": ["CCC", ["ddd", "Eee"], "fff", "GGG", ["111", "222"]], "test2": ["CCC"], "test4": "TESTV4",

"Test5": "OK"

}

8) $pull

Usage: $pull: {Field:value}}

Deletes an equal value from the array field. Cases:

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

{"_id": {"Floatapprox": {"}", "Count": "Test1": ["CCC", ["ddd", "Eee"], "fff", "GGG", ["111", "222"], "TE St2 ": [" CCC "]," test4 ":" TESTV4 ",

"Test5": "OK"}

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

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

{"_id": {"Floatapprox": "$", "Count": "Test1": ["CCC", ["ddd", "Eee"], "fff", ["111", "222"]], "test2": ["CCC"], "test4": "TESTV4", "Test5"

: "OK"}

9) $pullAll

Usage: {$pullAll: {Field:value_array}}

With $pull, you can delete multiple values within an array at a time. Cases:

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

{"_id": {"Floatapprox": "$", "Count": "Test1": ["CCC", ["ddd", "Eee"], "fff", ["111", "222"]], "test2": ["CCC"], "test4": "TESTV4", "Test5"

: "OK"}

> db.test0.update ({"_id":}, {$pullAll: {"test1": ["CCC", "FFF"]}});

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

{"_id": {"Floatapprox": "$", "Count": "Test1": [["ddd", "Eee"], ["111", "222"]], "test2": ["CCC"], "TE St4 ":" TESTV4 "," Test5 ":" OK "}

10) $ operator

$ is his own meaning, represented by the condition of finding an array inside an item of his own. Oh, compare the AU kou. Take a look at the official example:

> T.find ()

{"_id": ObjectId ("4b97e62bf1d8c7152c9ccb74"), "title": "ABC", "comments": [{"By": "Joe", "votes": 3}, {"By": "J Ane "," 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": "J Ane "," votes ": 7}]}

It is important to note that $ only applies the first array item found, followed by no 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 when used with $unset, a null array entry is left, but you can delete all null array items with {$pull: {x:null}}. Cases:

> 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. Elements within the array can be queried directly

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

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

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

3. Delete a column in the array and become null

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

4. Add an element to the array and create a new array if there are no previous elements

> db.arraytest.update ({' comments.id ': ' Reply22 '}, {$push: {' comments.$.reply ': {' rid ': ' R21 ', content: ' + '}}})

MongoDB Common Statements

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.