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.

原文地址:http://blog.51cto.com/395469372/2103695

时间: 2024-08-01 20:26:08

mongodb CRUD操作 -Select的相关文章

mongodb CRUD操作

# ./mongod 2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] MongoDB starting : pid=36578 port=27017 dbpath=/data/db 64-bit host=IBG-opensource-DB-cwT13 2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] db version v3.6.2 2018-04-15T18:52:

【翻译】MongoDB指南/CRUD操作(二)

[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关注),写确认(写关注) 1 更新文档 1.1 更新 MongoDB提供下列方法用于更新一个集合 db.collection.updateOne() 更新使用指定过滤器匹配到的文档,即使过滤器匹配到多个文档,也只会更新一个文档. 3.2版本新增特性. db.collection.updateMany(

【翻译】MongoDB指南/CRUD操作(一)

[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删除文档. 创建操作 执行创建或者插入操作可向集合中添加文档.如果集合不存在,插入操作会创建此集合. MongoDB提供下列方法向集合中插入文档: db.collection.insert() db.collection.insertOne()  3.2版本新增 db.collection.inser

MongoDB的CRUD操作

1. 前言 在上一篇文章中,我们介绍了MongoDB.现在,我们来看下如何在MongoDB中进行常规的CRUD操作.毕竟,作为一个存储系统,它的基本功能就是对数据进行增删改查操作. MongoDB中的增删改查操作,不同于我们熟悉的关系数据库中的操作.在关系数据库中,比如MySQL,我们通常使用SQL语句对数据库进行增(INSERT)删(DELETE)改(UPDATE)查(SELECT).MongoDB在对数据进行操作过程中,使用的是Document进行数据操作.在对数据库进行操作的时候,使用Do

【翻译】MongoDB指南/CRUD操作(三)

[原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近性,分布式查询(Distributed Queries),分布式写操作,模拟两阶段任务提交,在副本集中执行配额读取 1 原子性和事务(Atomicity and Transactions) 在MongoDB中,写操作在单文档级别具有原子性,即使修改一个文档中的多个嵌入式文档也是如此. 当一个写操作修

MongoDB对图片进行CRUD操作——与JAVA结合

上几篇博客简单对MongoDB进行了简单介绍和如何安装,以及在dos下是如何操作MongoDB和在安装MongoDB中,出现了什么错误,是如何解决的.当然这些都还不够,我们还要用到实际当中去.我用MyEclipse+JDK1.7做了一个简单的demo,来展示下MongoDB怎么运用到实际中去. MongoDB作为一个NoSql数据库的代表,存取多媒体数据,应该是强项吧?那么,在MongoDB中是如何对图片进行CRUD操作的. 上几篇博客中已经提到,MongoDB的文档结构是BSON格式,BSON

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

MongDB数据库的使用离不开CRUD操作.什么是CRUD,就是创建文档,读取文档信息,更新文档和删除文档. key-value键值对标记 在MongoDB的Ruby驱动中,Key_value键值多次出现.而且有时会出现语法上的巧合,这取决于在使用的Ruby版本中如何申明. 在文档创建步骤中,1.9及之后版本支持以下语法: document={name:"Tom",age:20}. 但是如果你使用的是2.2或者更高的版本,你可以用双引号将你的key包起来.如: document={&q

Mongodb的安装与CRUD操作

What is Mongodb ?         Mongo DB是一款开源的非关系型数据库(NoSql)其文档模型自由灵活,可以让你在开发过程中畅顺无比.对于大数据量.高并发.弱事务的互联网应用,MongoDB可以应对自如.MongoDB内置的水平扩展机制提供了从百万到十亿级别的数据量处理能力,完全可以满足Web2.0和移动互联网的数据存储需求,其开箱即用的特性也大大降低了中小型网站的运维成本. 安装Mongodb 来到mongodb官网http://www.mongodb.org/可以在这

MongoDB的一些简单CRUD操作

上篇博客已经对MongoDB进行了简单介绍和它如何安装,现在来说说MongoDB的操作.MongoDB的操作用的是Shell命令,Shell命令语法和JavaScript很类似,其实控制台底层的查询语句都是用JavaScript脚本完成操作的.使用Shell 命令,需要启动mongo.exe. 常用Shell命令如下: 1.创建collection 2.查看创建的collection 3.collection中写入数据 4.查询插入的数据 5.条件查询 6.查询一条数据中的指定列 7.排序 7.