mongodb CRUD操作 -Select

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongodb CRUD操作 -Select相关的知识,希望对你有一定的参考价值。

二、查询文档

方法:

db.collection.find()


Additional Methods

  • db.collection.findOne

  • In aggregation pipeline, the $match pipeline stage provides access to MongoDB queries.


db.inventory.insertMany([

  { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

  { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },

  { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

  { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

  { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

]);


1、Select All Documents in a Collection

db.inventory.find( {} )=db.inventory.find()


2、Specify Equality Condition

db.inventory.find( { status: "D" } )


SELECT * FROM inventory WHERE status = "D"


3、Specify Conditions Using Query Operators

db.inventory.find( { status: { $in: [ "A", "D" ] } } )


SELECT * FROM inventory WHERE status in ("A", "D")


4、Specify AND Conditions

db.inventory.find( { status: "A", qty: { $lt: 30 } } )


SELECT * FROM inventory WHERE status = "A" AND qty < 30


5、Specify OR Conditions

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )


SELECT * FROM inventory WHERE status = "A" OR qty < 30


6、Specify AND as well as OR Conditions

db.inventory.find( {

    status: "A",

    $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]

} )


SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")


Additional Query Tutorials

1、Query on Embedded/Nested Documents 查询嵌入/嵌套文档(字段值是一个文档)

db.inventory.insertMany( [

  { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

  { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },

  { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

  { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

  { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

])


Match an Embedded/Nested Document

查询size字段的值是{ h: 14, w: 21, uom: "cm" }的所有文档:在作为嵌入/嵌套文档的字段上指定相等条件

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

{ "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }

注:文档的精确匹配,包括顺序。


db.inventory.find({size:{w:21,h:14,uom:“cm”}})// 与集合中的任何文档不匹配


Query on Nested Field

Specify Equality Match on a Nested Field

查询size字段中嵌套的字段uom的值等于“in”的所有文档:

db.inventory.find( { "size.uom": "in" } )


Specify Match using Query Operator

查询size字段中嵌套的字段h的值小于15的所有文档:

db.inventory.find( { "size.h": { $lt: 15 } } )


Specify AND Condition

查询size字段中嵌套的字段h的值小于15,uom的值为“in”,status的值为“D”的所有文档:

db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )


2、Query an Array 查询数组(字段值是一个数组)

db.inventory.insertMany([

  { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },

  { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },

  { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },

  { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },

  { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }

])


Match an Array

查询数组字段tags中正好包含两个元素“red和blank”,并且顺序相同的所有文档:

db.inventory.find( { tags: ["red", "blank"] } )

注:精确匹配,包括数组中元素的顺序。


查询数组字段tags中包含“red”和“blank”两个元素的所有文档,不考虑数组中的顺序和其他元素:

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

等同于

db.inventory.find{ $and: [ { tags: "red" }, { tags: "blank" } ]


Query an Array for an Element

查询数组字段tags中包含red元素的所有文档:

db.inventory.find( { tags: "red" } )


查询数组字段dim_cm中至少有一个元素的值大于25的所有文档:

db.inventory.find( { dim_cm: { $gt: 25 } } )


Specify Multiple Conditions for Array Elements

Query an Array with Compound Filter Conditions on the Array Elements

查询数组字段dim_cn中一个元素的值大于15且另一个元素的值小于20,或者单个元素满足两个条件的所有文档

db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )


Query for an Array Element that Meets Multiple Criteria 查询符合多个标准的数组元素

查询数组字段dim_cm中至少有一个元素的值大于22且小于30的所有文档

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )


Query for an Element by the Array Index Position 通过数组索引位置查询元素

查询数组字段dim_cm中第二个元素的值大于25的所有文档:

db.inventory.find( { "dim_cm.1": { $gt: 25 } } )


Query an Array by Array Length

查询数组字段tags中具有三个元素的所有文档:

db.inventory.find( { "tags": { $size: 3 } } )


3、Query an Array of Embedded Documents 查询嵌入式文档的数组(字段值包含数组,数组里面嵌套文档)

db.inventory.insertMany( [

  { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },

  { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },

  { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },

  { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },

  { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }

])


Query for a Document Nested in an Array 查询嵌套在数组中的文档

查询数组字段instock中的嵌入式文档与指定文档匹配的所有文档:

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

注:精确匹配,包括字段的顺序。


db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } ) //与集合中的任何文档不匹配。


Specify a Query Condition on a Field in an Array of Documents 在文档数组中的字段上指定查询条件

Use the Array Index to Query for a Field in the Embedded Document 使用数组索引来查询嵌入文档中的字段

查询数组字段instock中第一个嵌入式文档中qty字段的值小于或等于20的所有文档:

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )


Specify a Query Condition on a Field Embedded in an Array of Documents 在文档数组中嵌入的字段上指定查询条件

查询数组字段instock中至少有一个嵌入式文档qty字段的值小于或等于20的所有文档:

db.inventory.find( { 'instock.qty': { $lte: 20 } } )


Specify Multiple Conditions for Array of Documents

A Single Nested Document Meets Multiple Query Conditions on Nested Fields 单个嵌套文档在嵌套字段上符合多个查询条件

查询数组字段instock中至少有一个嵌入式文档qty字段的值等于5并且warehouse字段的值等于A的所有文档:

db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )


查询数组字段instock中至少有一个嵌入式文档qty字段的值大于10小于20的所有文档:

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )


Combination of Elements Satisfies the Criteria 元素的组合满足标准

查询数组字段instock中至少有一个嵌入式文档的qty字段的值大于10,并且另一个嵌入式文档的qty字段的值小于或等于20的所有文档,或者同时满足两个条件:

db.inventory.find( { "instock.qty": { $gt: 10,  $lte: 20 } } )


查询数组字段instock中至少有一个嵌入式文档的qty字段的值等于5,并且另一个嵌入式文档的warehouse字段的值是A的所有文档,或者同时满足两个条件:

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" }) )


4、Project Fields to Return from Query 从查询结果中返回指定的字段

db.inventory.insertMany( [

 { item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },

 { item: "notebook", status: "A",  size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },

 { item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },

 { item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },

 { item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }

])


Return All Fields in Matching Documents

db.inventory.find( { status: "A" } )


SELECT * from inventory WHERE status = "A"


Return the Specified Fields and the _id Field Only

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )


SELECT _id, item, status from inventory WHERE status = "A"

by default, the _id fields return in the matching documents.


Suppress _id Field

db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )


SELECT item, status from inventory WHERE status = "A"


Return All But the Excluded Fields

db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )


With the exception of the _id field, you cannot combine inclusion and exclusion statements in projection documents.


Return Specific Fields in Embedded Documents

size字段只返回嵌入式文档中的uom字段:

db.inventory.find(

  { status: "A" },

  { _id:0,item: 1, status: 1, "size.uom": 1 }

)


Suppress Specific Fields in Embedded Documents

size字段不返回嵌入式文档中的uom字段:

db.inventory.find(

  { status: "A" },

  { "size.uom": 0 }

)


Projection on Embedded Documents in an Array 嵌入式文档在数组中的投影

数组字段instock只返回嵌入式文档中的qty字段:

db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )


Project Specific Array Elements in the Returned Array

数组字段instock只返回最后一个元素:

db.inventory.find( { status: "A" }, { _id:0,item: 1, status: 1, instock: { $slice: -1 } } )


5、Query for Null or Missing Fields 查询null或空值

db.inventory.insertMany([

  { _id: 1, item: null },

  { _id: 2 }

])


Equality Filter

db.inventory.find( { item: null } )

{ "_id" : 1, "item" : null }

{ "_id" : 2 }


Type Check

db.inventory.find( { item : { $type: 10 } } ) //指定类型

{ "_id" : 1, "item" : null }


Existence Check

db.inventory.find( { item : { $exists: false } } )

{ "_id" : 2 }


查询和投影操作符

Comparison Query Operators

$eq        Matches values that are equal to a specified value.


$gt        Matches values that are greater than a specified value.


$gte        Matches values that are greater than or equal to a specified value.


$lt        Matches values that are less than a specified value.


$lte        Matches values that are less than or equal to a specified value.


$ne        Matches all values that are not equal to a specified value.

db.inventory.find( { qty: { $ne: 20 } } )

This query will select all documents in the inventory collection where the qty field value does not equal 20, including those documents that do not contain the qty field.


$in        Matches any of the values specified in an array.

$in操作符选择字段的值等于指定数组中的任何值的文档。

db.inventory.find( { qty: { $in: [ 5, 15 ] } } )


$nin        Matches none of the values specified in an array.

$nin selects the documents where:

  • the field value is not in the specified array or

  • the field does not exist.

db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )


Logical Query Operators

$or        Joins query clauses with a logical OR returns all documents that match the conditions of either clause.


$and        Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.


$not        Inverts the effect of a query expression and returns documents that do not match the query expression.

返回与查询表达式不匹配的文档。

db.inventory.find( { price: { $not: { $gt: 1.99 } } } )

  • the price field value is less than or equal to 1.99 or

  • the price field does not exist


$nor        Joins query clauses with a logical NOR returns all documents that fail to match both clauses.

使用逻辑NOR连接查询子句返回所有不匹配两个子句的文档。

db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ]  } )

  • contain the price field whose value is not equal to 1.99 and contain the sale field whose value is not equal to true or

  • contain the price field whose value is not equal to 1.99 but do not contain the sale field or

  • do not contain the price field but contain the sale field whose value is not equal to true or

  • do not contain the price field and do not contain the sale field


db.inventory.find( { $nor: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } )

  • the price field value does not equal 1.99 and

  • the qty field value is not less than 20 and

  • the sale field value is not equal to true

including those documents that do not contain these field(s).


Element Query Operators 元素查询操作符

$exists  Matches documents that have the specified field.

{ a: 5, b: 5, c: null }

{ a: 3, b: null, c: 8 }

{ a: null, b: 3, c: 9 }

{ a: 1, b: 2, c: 3 }

{ a: 2, c: 5 }

{ a: 3, b: 2 }

{ a: 4 }

{ b: 2, c: 4 }

{ b: 2 }

{ c: 6 }


db.records.find( { a: { $exists: true } } )

{ a: 5, b: 5, c: null }

{ a: 3, b: null, c: 8 }

{ a: null, b: 3, c: 9 }

{ a: 1, b: 2, c: 3 }

{ a: 2, c: 5 }

{ a: 3, b: 2 }

{ a: 4 }


db.records.find( { b: { $exists: false } } )

{ a: 2, c: 5 }

{ a: 4 }

{ c: 6 }


$type  Selects documents if a field is of the specified type.


Projection Operators

$

The positional $operator limits the contents of an <array> from the query results to contain only the first element matching the query document.

位置$运算符将查询结果中的<array>的内容限制为仅包含与查询文档匹配的第一个元素。

{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] }

{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] }

{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }

{ "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80 ] }

{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] }

{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }


db.students.find( { semester: 1, grades: { $gte: 85 } },

                 { "grades.$": 1 } )

{ "_id" : 1, "grades" : [ 87 ] }

{ "_id" : 2, "grades" : [ 90 ] }

{ "_id" : 3, "grades" : [ 85 ] }


{ "_id" : 7, semester: 3, "grades" : [ { grade: 80, mean: 75, std: 8 },

                                      { grade: 85, mean: 90, std: 5 },

                                      { grade: 90, mean: 85, std: 3 } ] }


{ "_id" : 8, semester: 3, "grades" : [ { grade: 92, mean: 88, std: 8 },

                                      { grade: 78, mean: 90, std: 5 },

                                      { grade: 88, mean: 85, std: 3 } ] }


db.students.find(

  { "grades.mean": { $gt: 70 } },

  { "grades.$": 1 }

)

//返回grades字段中mean值大于70的第一个元素:

{ "_id" : 7, "grades" : [  {  "grade" : 80,  "mean" : 75,  "std" : 8 } ] }

{ "_id" : 8, "grades" : [  {  "grade" : 92,  "mean" : 88,  "std" : 8 } ] }


$elemMatch

The $elemMatch operator limits the contents of an <array> field from the query results to contain only the first element matching the $elemMatch condition.

$elemMatch操作符将查询结果中的<array>字段的内容限制为仅包含与$elemMatch条件匹配的第一个元素。

{

_id: 1,

zipcode: "63109",

students: [

             { name: "john", school: 102, age: 10 },

             { name: "jess", school: 102, age: 11 },

             { name: "jeff", school: 108, age: 15 }

          ]

}

{

_id: 2,

zipcode: "63110",

students: [

             { name: "ajax", school: 100, age: 7 },

             { name: "achilles", school: 100, age: 8 },

          ]

}

{

_id: 3,

zipcode: "63109",

students: [

             { name: "ajax", school: 100, age: 7 },

             { name: "achilles", school: 100, age: 8 },

          ]

}

{

_id: 4,

zipcode: "63109",

students: [

             { name: "barney", school: 102, age: 7 },

             { name: "ruth", school: 102, age: 16 },

          ]

}


db.schools.find( { zipcode: "63109" },

                { students: { $elemMatch: { school: 102 } } } )

{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }

{ "_id" : 3 }

{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }

  • For the document with _id equal to 1, the students array contains multiple elements with the school field equal to 102. However, the $elemMatch projection returns only the first matching element from the array.

  • The document with _id equal to 3 does not contain the students field in the result since no element in its students array matched the $elemMatch condition.


db.schools.find( { zipcode: "63109" },

                { students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )

{ "_id" : 1, "students" : [ { "name" : "jess", "school" : 102, "age" : 11 } ] }

{ "_id" : 3 }

{ "_id" : 4, "students" : [ { "name" : "ruth", "school" : 102, "age" : 16 } ] }

The document with _id equal to 3 does not contain the students field since no array element matched the $elemMatch criteria.



以上是关于mongodb CRUD操作 -Select的主要内容,如果未能解决你的问题,请参考以下文章

MongoDB学习笔记-使用 MongoDB 进行 CRUD 操作(上)

MongoDB学习笔记-使用 MongoDB 进行 CRUD 操作(下)

为 MongoDB 上的 CRUD 操作组织 Go 代码

Mongodb crud操作

Ruby操作MongoDB(进阶)-CRUD操作

mongodb的CRUD操作三