MongoDB query operation (I) (ii): mongodb query operation

Source: Internet
Author: User
Tags mongodb query

MongoDB query operation (I) (ii): mongodb query operation
I. Introduction

MongoDB provides db. collection. the find () method is to query the document set and the db that returns the result as a cursor. collection. the findOne () method returns only the first record, instead of the document set that returns the cursor.

Db. collection. find () can be used to query based on conditions and specify fields returned using the projection operator to omit this parameter to return all fields in the matching document. The cursor of the matched document is returned. You can modify the query restrictions, jumps, and sorting order at will.


Ii. db. collection. find () query data

Syntax

<span style="font-size:18px;"> db.collection.find(query,projection)</span>

 

Parameters

Type

Description

Query

Document

Optional. Use the query operator to specify the query conditions.

Projection

Document

Specifies that the field returned by the projection operator is omitted. This parameter returns all fields in the matching document.

 

Projection Syntax:

 

<span style="font-size:18px;">{ field1: <boolean>, field2: <boolean> ... }</span>


 

Note:

1 Or true indicates the returned Field

0 or false indicates that this field is not returned.

 

_ Id: The default value is 1. If this field is not specified, it is returned by default. This field is not returned unless it is set to 0.

Specify the returned field. Sometimes, when there are many file fields and a large amount of data, we specify to return the required fields. This not only saves the amount of data transmitted, reduces memory consumption, but also improves performance. When the data size is large, the performance is obvious.

1. query data

(1) return all documents in the collection:

Db. collection. find ()

Or

Db. collection. find ({})



Like SQL statements:

SELECT * FROM TABLENAME






(2) Specify that the field returned by the projection operator is omitted. This parameter returns all fields in the matching document.

Syntax:

         db.orders.find({},{field1: <boolean>, field2: <boolean> ... })


Example:

      db.orders.find({},{"onumber":1,"cname":1})



The default value of _ id is 1, and all values are returned.

 

You can set _ id to not return

Example:


    db.orders.find({},{"onumber":1,"cname":1,"_id":0})



 

2. query by condition (1) equal to the condition Query

Syntax:

     db.collect.find({<field1>: <value1>,<field2>: <value2>, ... })



Example:

 

    db.orders.find({"onumber":"002"})




Search for documents with onumber = 002

 

(2) Comparison Operators

 

$ Gt (greater than), $ gte (greater than or equal to), $ lt (less than), $ lte (less than or equal)


Syntax:

 

    { <field1>: { <expression1> },<field2>: {<expression1> }, ... }

 

1) $ gt (greater than) comparison operator

 

Example:

     db.orders.find({"onumber":{$gt:"003"}})

We can find that the onumber> 003 value is only 004.

 

2) $ gte (greater than or equal to) and $ lte (less than or equal to) join query and specify the returned field (through the second parameter)

 

Example:

      db.orders.find({"onumber":{$gte:"002",$lte:"003"}},{"onumber":1,"cname":1})

 

We can find 002 = <onumber <= 003 and specify the returned onumber and cname fields, while _ id is set to 1 by default, and all return

 

(3) $ or, and $ and condition Query

1) $ and condition Query

Syntax:

       { $and: [ { <expression1> }, { <expression2> } , ... , ]}

Simple Syntax:

   { <field1>: <value1>,<field2>: <value2>, ...}


Example:

    db.orders.find({"onumber":"002","cname":"zcy2"})

Search for onumber = 002 AND cname = zcy2

2) $ or (or) condition Query

Syntax:

       { $nor: [ { <expression1> }, { <expression2> }, ... ] }

Example:

     db.orders.find({$or:[{"onumber":"002"},{"cname":"zcy1"}]})

 

Search for documents that meet the onumber = 002 OR cname = zcy1 Condition

 

 3) $ or and $ and join condition Query

Example:

     db.orders.find({$and:[{"date":"2015-07-01"},{$or:[{"onumber":"002"},{"cname":"zcy1"}]}]})

The document with the query condition date = and (onumber = 002 OR cname = zcy1) is equivalent to date = and must meet the condition that onumber is equal to 002 OR cname is equal to zcy1.

(4) $ in (inclusive) and $ nin (excluded) condition queries

1) $ in (including) condition Query


Syntax:

          { field: { $in: [<value1>, < value2>, ...] } }

Example:

         db.orders.find({"onumber":{$in:["001","002"]}})

The document that queries the onumber in ("001", "002") condition is that the onumber equals 001 or 002, which is a bit like $ or, but $ or is used as the condition query, you can specify different fields: db. orders. find ({$ or: [{"onumber": "002" },{ "cname": "zcy1"}]})

And $ in only applies to one field.


2) $ nin (not included) condition Query

Syntax:

         { field: { $nin: [<value1>, < value2>, ...] } }

$ Nin (not included) is the opposite of $ in (included ).

 

(5) $ not (not equal to) condition Query

Syntax:

      { field: { $not: { < expression1> } } }


The $ not operator cannot be used independently and must be used together with other operation conditions (except $ regex)


Example:

     db.orders.find({"onumber":{$not:{$gt:"002"}}})

Search for document data whose onumber is not equal to 002

 

(6) $ exists is used to determine whether a field exists.

Syntax:

       { field: { $ exists:  < boolean>  } }


Example:

        db.orders.find({"age":{$exists:true}})


 

Without the age element, nothing is returned.

 

Insert the age element. Run the following command.


 

 

(7) $ mod modulo and equal to the specified value

Syntax:

     { field: { $mod: [ value, value2 ]} }

Modulo the element field value to the value. The modulo value must be value2 document data.

 

Example:

    db.orders.find({"age":{$mod:[5,1]}})

For the value of the age element and the modulo value of 5, the modulo value must be equal to 1 of the document data.

 

(8) null searches for documents where the element does not exist and its corresponding value is null.

Syntax:

{Field: null}

Example:

      db.orders.find({"age":null})


1) find that the age element exists and the value is null.

        db.orders.find({"age":{$in:[null],$exists:true}})

(9) $ type to match the type of an element

Syntax:

{Field :{$ type: <number> }}

 

Number is the type value corresponding to the type used in MongoDB.

Type

Type Value

Double

1

String

2

Object

3

Array

4

Binary data

5

Undefined (deprecated)

6

Object id

7

Boolean

8

Date

9

Null

10

Regular Expression

11

JavaScript

13

Symbol

14

JavaScript (with scope)

15

32-bit integer

16

Timestamp

17

64-bit integer

18

Min key

255

Max key

127

 

2. query arrays based on conditions

 

$ All, $ size, $ where, $ slice, $ elemMatch

(1) $ all search for documents with specified values in the array

Syntax:

{Field :{$ all: [<value >,< value1>...]}

Example:

Db. orders. find ({"books": {$ all: ["java", "mongo"]})

Search for documents whose books contain java and mongo

 

(2) $ size: search for documents whose array size is equal to the specified value

Syntax:

    {field: {$size: number } }


Example:

    db.orders.find({"books":{$size:2}})

 

(3) $ slice query the number of returned elements specified in the array

Syntax:

         db.collect.find({},{field:{$slice: number }})

 

Number Description:

If the number is positive, the number of the previously specified values is returned. For example, 1 returns the first value of the array.

If it is a negative number, the number of values specified to the last is returned. For example,-1 returns the first to the last value of the array.

 

Example:

       db.orders.find({"onumber":{$in:["008","009"]}},{books:{$slice:1}})

 

 

 1) $ slice can query the number to number in the array

Syntax:

        db.collect.find({},{field:{$slice:[ number1, number2] }})


Skip the number1 position of the array and return the number of number2.

Number1 description:

A positive number indicates the number of arrays that are jumped to the specified value. For example, 2 indicates the number of arrays that are jumped to the specified value.

If it is a negative number, it indicates that the number of records to which an array belongs is exceeded. For example,-2 indicates that the number of records to which an array belongs is exceeded.

 

Example:

        db.orders.find({"onumber":{$in:["008","009"]}},{books:{$slice:[1,1]}})



Skip the first element of the books array. Now, the second element of the array is skipped, and 1 element is returned.

 

 

3. query embedded array documents

 db. orders.insert([{        "onumber" : "001",         "date" : "2015-07-02",         "cname" : "zcy1",          "items" :[ {                   "ino" : "001",                  "quantity" :2,                   "price" : 4.0                 },{                   "ino" : "002",                  "quantity" : 4,                   "price" : 6.0                }                ]},{         "onumber" : "002",         "date" : "2015-07-02",         "cname" : "zcy2",          "items" :[ {                  "ino" : "001",                  "quantity" :2,                   "price" : 4.0                   },{                  "ino" : "002",                  "quantity" :6,                   "price" : 6.0                 }               ]}])


(1) $ elemMatch contains an array, so $ elemMatch can match the elements in the array and return document data.

Syntax:

       {field:{$elemMatch:{ field1:value1, field2:value2,………}}}

 

Example:

    db.orders.find({"items":{$elemMatch:{"quantity":2}}})

Returns the document whose quantity is 2.

 

You can also query db. orders. find ({"items. quantity": 2 })

 

2) $ elemMatch can contain multiple query Conditions

Example:

   db.orders.find({"items":{$elemMatch:{"quantity":4,"ino":"002"}}}) 

 

We query the document in which quantity is 4 and ino is 002, but we want to return the document in which quantity is 4 and ino is 002, we do not want to return irrelevant documents such as ino and 001.

 

 

3) $ elemMatch can also be used in the second parameter of the find method to limit the elements in the returned array. Only the required documents are returned.

Example:

Db. orders. find ({"onumber": "001" },{ "items" :{$ elemMatch: {"quantity": 4, "ino": "002 "}}, "cname": 1, "date": 1, "onumber": 1 })

We only return documents whose quantity is 4 and whose ino is 002. unrelated documents are not returned, which facilitates data processing. This reduces the amount of data transmitted, reduces memory consumption, and improves performance, when the data is large, the performance is obvious.



Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.