Mongodb Array Query

Source: Internet
Author: User
Tags findone mongodump mongorestore

Inserting more than one test data
> for (i=1;i<=1000;i++) {
... db.blog.insert ({"title": I, "content": "MongoDB Test article. "," name ":" Liu "+i});
... }

Db.blog.list.find (). Limit ((). ForEach (function (data) {print ("title:" +data.title);}) Cyclic foreach usage

Db.blog.findOne (); Fetch a piece of data

Db.blog.find (); take more than one data
Db.blog.remove (); Delete a data set
Db.blog.drop (); Delete table

To delete a database:
1.use dbname
2.db.dropdatabase ()


====================================== Query Operation =============================
Db.blog.find () equivalent to select * FROM blog
Db.blog.find ({"Age": 27}) equivalent to select * from blog where age= ' 27 '
Db.blog.find ({"Age": +, "name": "Xing"}) equals select * from blog where age= ' and name= ' Xing '
Db.blog.find ({},{"name": 1}) select name from blog, if name:0 does not display the name field
Db.blog.find (). Limit (1) equals select * FROM blog limit 1

Db.blog.find (). Sort ({_id:-1}). Limit (1) equals select * from blog ORDER BY _id DESC LIMIT 1
Db.blog.find (). Skip (20) equals select * FROM blog limit 10,20
Skip use, it is important to note that if the number of words skip will become very slow, all the database has this problem, you can skip paging, with the last record as a condition
Db.blog.find ({"Age": {"$gte": +, "$lte": ()}) select * from blog where age>=27 and age<=50
$GT >
$gte >=
$lt <
$lte <=
$ne! =
$in: In
$nin: Not in
$all: All
$not: Anti-match

Query Creation_date > 2010-01-01 ' and creation_date <= ' 2010-12-31 ' data
Db.users.find ({creation_date:{$gt: new Date (2010,0,1), $lte: new Date (2010,11,31)});

Db.blog.find (). Sort ({_id:-1}) is equivalent to select * from the blog order by _id DESC in reverse order by _ID Data 1 is the positive sequence, multiple conditions with, number separated as {name:1,age:-1}
Db.blog.find ({"_id": {"$in", [12,3,100]}}) is equivalent to select * from the blog where _id in (12,3,100)
Db.blog.find ({"_id": {"$nin", [12,3,100]}}) is equivalent to select * from the blog where _id not in (12,3,100)
Db.blog.find ({"$or": [{"Age": 16},{"name": "Xing"}]}) is equivalent to select * from the blog where age = + or name = ' Xing '
Db.blog.find ({"Id_num": {"$mod": [5,1]}) takes a field of id_num mod 5 = 1, such as id_num=1,6,11,16
Db.blog.find ({"Id_num": {"$not": {"$mod": [5,1]}}) takes a field of Id_num mod 5! = 1, such as all fields except id_num=1,6,11,16, more than regular one

$exists determine if a field exists

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


$type Judging field Types
Query all name fields are of character type
Db.users.find ({name: {$type: 2}});
Query all age fields are integral type
Db.users.find ({age: {$type: 16}});


Db.blog.find ({"Z": null}) returns all records with no z fields
Db.blog.find ({"Name":/^joe/i}) finds all records for Name=joe, case insensitive

Db.blog.distinct (' content ') to check the specified column and go to heavy


Querying arrays
Db.blog.find ({"Fruit": {"$all": ["apple", "peach", "Pear"]}}) fruit must have each of the arrays in order to match the result
Db.blog.find ({"Fruit": {"$size": 3}}) fruit array with a length of 3 matches the result
Db.blog.find ({"$push": {"fruit": "Orange"}}) equals Db.blog.find ({"$push": {"fruit": "Orange"}, "$inc": {"size": 1}})
$slice can return records by offset, for arrays. If {"$slice": 10} returns the first 10, {"$slice": {[23,10]}} fetch 10 from 24 strips
If an object has an element that is an array, then $elemmatch can match the elements within the array

Db.people.find ({"Name.first": "Joe", "Name.last": "Schmoe"}) subquery such as: {"id": "name": {"First": "Joe", "Last": "Schmoe"}}

Db.blog.find ({"Comments": {"$elemMatch": {"author": "Joe", "score": {"$gte": 5}}}) Check Joe for more than 5 comments, notice that comments is a two-dimensional array
$where can be used in desperate times, but its efficiency is very low.


Cursor usage
Cursor.hasnext () checks to see if any subsequent results exist, and then uses Cursor.next () to obtain them.
>while (Cursor.hasnext ()) {
var obj = Cursor.next ();
Do same
}

Http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ConditionalOperators%3A%3C%2C%3C%3D%2C%3E%2C%3E%3D Handbook

> Use Blog
> Db.blog.insert ({"title": "Huaxia Star Blog", "Content": "MongoDB Test article. "});
> Db.blog.find ();
{"_id": ObjectId ("4E29FD262ED6910732FA61DF"), "title": "Huaxia Star Blog", "Content": "MongoDB Test article." " }
> db.blog.update ({title: "Huaxia star's Blog"},{"author": "Star", "Content": "Test Update"});
> Db.blog.find ();
{"_id": ObjectId ("4E29FD262ED6910732FA61DF"), "author": "Star", "Content": "Test Update"}

Db.blog.insert display source without parentheses
Db.blog.insert (); insert
Db.blog.update (); update

> db.blog.update ({title: "Huaxia star's Blog"},{"author": "Star", "Content": "Test Update"});

Update by default, you can only perform actions on the first document that meets the criteria, and to make all matching documents updated, set the fourth parameter to True

> db.blog.update ({title: "Huaxia star's Blog"},{"author": "Star", "Content": "Test Update"},false,true);

> Db.runcommand ({getlasterror:1}) can see a few updated information, n is the number of bars

Back up the blog database to the/soft directory
/usr/local/webserver/mongodb/bin/mongodump-d Blog-o/soft

Restoring a Database

/usr/local/webserver/mongodb/bin/mongorestore-d blog-c Blog/soft/blog/blog.bson

Export the database (the backed up data is binary and has been compressed.) )
/usr/local/webserver/mongodb/bin/mongodump-h 127.0.0.1-port 27017-d Demo-o/tmp/demo
Import data
/usr/local/webserver/mongodb/bin/mongorestore-h 127.0.0.1-port 27017--directoryperdb/tmp/demo


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.

8) $type

$type match the type of an element based on Bson type, as if it were matched by type ID, but I didn't find the Bson type and ID table.

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"})


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

http://www.bumao.com/index.php/mongo_and_php

http://www.php.net/manual/en/mongocursor.count.php

Mongodb Array Query

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.