`

MongoDB Dot Notation (Reaching into Objects)

阅读更多
转载自  http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)


Dot Notation (Reaching into Objects)
Dot Notation vs. Subobjects
Array Element by Position
Matching with $elemMatch
See Also
MongoDB is designed for storing JSON-style objects.  The database understands the structure of these objects and can reach into them to evaluate query expressions.

Let's suppose we have some objects of the form:

> db.persons.findOne()
{ name: "Joe", address: { city: "San Francisco", state: "CA" } ,
  likes: [ 'scuba', 'math', 'literature' ] }
Querying on a top-level field is straightforward enough using Mongo's JSON-style query objects:

> db.persons.find( { name : "Joe" } )
But what about when we need to reach into embedded objects and arrays?  This involves a bit different way of thinking about queries than one would do in a traditional relational DBMS.  To reach into embedded objects, we use a "dot notation":

> db.persons.find( { "address.state" : "CA" } )
Reaching into arrays is implicit: if the field being queried is an array, the database automatically assumes the caller intends to look for a value within the array:

> db.persons.find( { likes : "math" } )
We can mix these styles too, as in this more complex example:

> db.blogposts.findOne()
{ title : "My First Post", author: "Jane",
  comments : [{ by: "Abe", text: "First" },
              { by : "Ada", text : "Good post" } ]
}
> db.blogposts.find( { "comments.by" : "Ada" } )
We can also create indexes of keys on these fields:

db.persons.ensureIndex( { "address.state" : 1 } );
db.blogposts.ensureIndex( { "comments.by" : 1 } );
Dot Notation vs. Subobjects

Suppose there is an author id, as well as name. To store the author field, we can use an object:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
If we want to find any authors named Jane, we use the notation above:

> db.blog.findOne({"author.name" : "Jane"})
To match only objects with these exact keys and values, we use an object:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
Note that

db.blog.findOne({"author" : {"name" : "Jane"}})
will not match, as subobjects have to match exactly (it would match an object with one field: {"name" : "Jane"}). Note that the embedded document must also have the same key order, so:

db.blog.findOne({"author" : {"id" : 1, "name" : "Jane"}})
will not match, either. This can make subobject matching unwieldy in languages whose default document representation is unordered.

Array Element by Position

Array elements also may be accessed by specific array position:

// i.e. comments[0].by == "Abe"
> db.blogposts.find( { "comments.0.by" : "Abe" } )
(The above examples use the mongo shell's Javascript syntax.  The same operations can be done in any language for which Mongo has a driver available.)

Matching with $elemMatch

Using the $elemMatch query operator (mongod >= 1.3.1), you can match an entire document within an array. This is best illustrated with an example. Suppose you have the following two documents in your collection:

// Document 1
{ "foo" : [
      {
        "shape" : "square",
        "color" : "purple",
        "thick" : false
      },
      {
        "shape" : "circle",
        "color" : "red",
        "thick" : true
      }
] }


// Document 2
{ "foo" : [
      {
        "shape" : "square",
        "color" : "red",
        "thick" : true
      },
      {
        "shape" : "circle",
        "color" : "purple",
        "thick" : false
      }
] }
You want to query for a purple square, and so you write the following:

db.foo.find({"foo.shape": "square", "foo.color": "purple"})
The problem with this query is that it will match the second in addition to matching the first document. In other words, the standard query syntax won't restrict itself to a single document within the foo array. As mentioned above, subobjects have to match exactly, so

db.foo.find({foo: {"shape": "square", "color": "purple"} } )
won't help either, since there's a third attribute specifying thickness.

To match an entire document within the foo array, you need to use $elemMatch. To properly query for a purple square, you'd use $elemMatch like so:

db.foo.find({foo: {"$elemMatch": {shape: "square", color: "purple"}}})
The query will return the first document, which contains the purple square you're looking for.
分享到:
评论

相关推荐

    mongodb-docs-2011-01-29_mongodb最新用户手册

    - **Dot Notation**:解释了 MongoDB 中的点符号表示法,这是进行嵌套文档查询的基础。 综上所述,《mongodb-docs-2011-01-29_mongodb最新用户手册》是一份详尽的手册,旨在为用户提供全面的技术支持和指导,覆盖了...

    linux安装mongodb教程

    /usr/local/mongodb/mongodb-linux-2.0.7/bin/mongod --dbpath=/usr/local/mongodb/data/db --logpath=/usr/local/mongodb/mongodb-linux-2.0.7/logs/mongodb.log --logappend --port=27017 --fork 知识点 6:配置...

    五、MongoDB 学习PPT

    在MongoDB中,数据是以文档的形式存储的,这些文档是由键值对组成的,并且通常以JSON(JavaScript Object Notation)或BSON(Binary JSON)格式表示。BSON是一种二进制形式的JSON,允许更快的数据传输和更小的存储...

    MongoDB Days 2015 深圳 PPT 共享

    1. **文档型数据库**: MongoDB是基于文档的数据库,这意味着它存储数据为JSON(JavaScript Object Notation)格式的文档,这种格式便于存储复杂的数据结构,如嵌套对象和数组。 2. **弹性伸缩**: MongoDB支持水平...

    mongodb-测试数据

    MongoDB是一种流行的开源、分布式文档数据库,常被用于构建高性能、可扩展的应用程序。这个“mongodb-测试数据”压缩包显然包含了一些用于测试MongoDB功能的样例数据集,特别是针对增、删、改、查(CRUD)操作的学习...

    mongoDB说明文档

    点记法(Dot Notation)** 点记法是MongoDB中用于访问和操作嵌套文档的一种方法。理解和熟练运用点记法,对于高效查询和更新复杂数据结构至关重要。 ### **17. 软件获取(Getting the Software)** 这部分内容指导...

    MongoDB实验 - .docx

    MongoDB 实验报告 本实验报告旨在详细介绍 MongoDB 的安装、配置和基本操作步骤,本报告基于 CentOS 7 系统,通过一步一步的截图和文字说明,帮助读者快速掌握 MongoDB 的使用。 一、安装 MongoDB 首先,我们需要...

    mongoDB的官方中文文档

    1. **数据模型**:MongoDB的数据模型基于JSON(JavaScript Object Notation)格式,文档由键值对组成,键是字符串,值可以是各种类型,包括其他文档、数组等。这种数据模型非常适合处理半结构化和非结构化数据。 2....

    Linux安装mongodb客户端

    sudo vim /etc/yum.repos.d/mongodb-org-4.2.repo 写入: [mongodb-org-4.2] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/ gpgcheck=1 enabled=1 gpg...

    MongoDB图形化管理工具 MongoDB Compass

    MongoDB图形化管理工具 MongoDB Compass

    mongodb Windows7 64位

    MongoDB是一款开源、高性能、无模式的文档型数据库,它在现代应用程序开发中扮演着重要的角色,特别是在处理大量非结构化数据时。针对"mongodb Windows7 64位"这个主题,我们将深入探讨MongoDB在Windows 7 64位操作...

    mongodb c#驱动最新驱动mongodb.driver.dll 版本2.12.0-beta1

    MongoDB 是一个流行的开源、基于分布式文件存储的数据库系统,主要设计用于处理大量数据的分布式环境。C# 驱动是 MongoDB 提供的一种客户端库,允许 .NET 开发者与 MongoDB 数据库进行交互。标题提到的是 MongoDB 的...

    MongoDB入门指南.pdf

    MongoDB入门指南 MongoDB是一种开源的文档类型数据库,它具有高性能、可扩展、高可用、自动收缩等特性。MongoDB能够避免传统的ORM映射,从而有助于开发。MongoDB中的每一行记录就是一个文档,它是一个由键值对构成...

    spring-data使用mongodbTemplate对MongoDB进行读写操作

    Spring Data MongoDB是一个强大的Java库,它为开发人员提供了一种简单的方式来访问和操作MongoDB数据库。这个库是Spring Data框架的一部分,旨在简化数据访问层的实现,尤其在使用NoSQL数据库如MongoDB时。MongoDB...

    mongodb.dll 下载.zip

    MongoDB是一个开源、分布式、高性能的NoSQL数据库,以其灵活性、可扩展性和高可用性而闻名。`mongodb.dll`是MongoDB数据库系统在Windows平台上运行所必需的一个动态链接库(DLL)文件,它包含了MongoDB客户端和...

    Centos7下安装MongoDB

    安装MongoDB需要安装mongodb-org元数据包,该包包含四个组件包:mongodb-org-server、mongodb-org-mongos、mongodb-org-shell、mongodb-org-tools。 在Centos7下安装MongoDB可以通过epel-release的yum源来安装,...

    mongodb数据库jar包

    MongoDB是一个流行的开源、分布式文档型数据库,设计用于处理大量数据并提供高可用性和高性能。在Java应用程序中,为了与MongoDB进行交互,我们需要使用Java MongoDB驱动程序。这个压缩包包含的就是Java连接MongoDB...

    7_webstorm配置mongodb1

    MongoDB是一款面向文档的NoSQL数据库,使用BSON(Binary Serialized Object Notation)存储数据。它具有高性能、高可用性和可扩展性,常用于大数据分析、实时分析、机器学习和人工智能等领域。 WebStorm配置...

    mongodb.zip

    相反,它使用文档模型来存储数据,文档是JSON(JavaScript Object Notation)格式的对象,这种模型更适合处理半结构化和动态模式的数据。 2. **分布式架构**: MongoDB设计为分布式系统,可以跨多个服务器、网络甚至...

Global site tag (gtag.js) - Google Analytics