Home Database Mysql Tutorial MongoDB基本查询整理

MongoDB基本查询整理

Jun 07, 2016 pm 05:20 PM
mongodb database

精确匹配 单个键值对:{age:28}, 返回age值为28的所有文档。 多个键值对:{username:tom, age:28},将多个查询条件

精确匹配

  • 单个键值对:{"age":28}, 返回"age"值为28的所有文档。
  • 多个键值对:{"username":"tom", "age":28},将多个查询条件组合在一起,等同于:条件1 AND 条件2 AND …AND 条件N。该查询文档返回:用户名为tom,并且年龄为28的所有文档。
  • 条件匹配 范围
  • “$lt”、“$lte”、“$gt”、“$gte”
    比较操作符,分别对应:
    $gt >= $gte
    可以组合起来查找一个范围内的值。
    如:年龄在18到35之间的查询文档是:{"age": {"$gte":18, "$lte":35}}
    该范围查询方式对日期类型值尤为方便。
  • “$ne” 
    “不相等”操作符,对应:!=
    如用户名不是tom的查询文档是: {"username": {"$ne":"tom"}}
  • OR查询
  • $in
    用来查询一个键对应的多个值,对单个键做OR查询。
    如:活动中奖号码是1,4,8,要找出全部这些中奖数据的查询文档是:{"ticket_no":{"$in":[1, 4, 8]}}
  • $nin
    相对地,$nin返回与数组中值都不符合的数据,如找出没有中奖的数据的查询文档是:{ "ticket_no": {"$nin": [1, 4, 8]} }。
  • $or
    用来查询多个键的任意值,会更通用一些。它接受一个所有可能条件的数组作为参数,也可以含有其他条件句。如:
    { "$or": [ { "ticket_no":{ "$in":[1, 4, 8] } }, { "winner":true } ] }
    $or的第一个条件应尽可能地匹配更多的文档,这样才最有效。
  • $not

    $not是元条件句,可以用在任何其他条件之上,表取反。
    如:查询文档:{"value":{"$mod":[5,1]}},符合条件的值有:1, 6, 11等。
    如果想要查找值为2, 3, 4, 5, 7, 8, 9, 10, 12等的数据就可以用:{"value":{"$not":{"$mod":[5,1]}}}。

    $exists

    用来查询文档中某个键是否存在,,如找出不存在键名为key1的文档:{"key1":{"$exists":false}};
    相反,{"key1":{"$exists":true}}表示存在key1键。

    类型匹配 Null

    查询文档{"x":null},执行后返回:包含有键值对“x”:null的文档,以及不存在x键的文档。

    正则表达式

    PCRE支持的正则表达式都能被MongoDB所接受。
    如查询文档{key1”} 都会返回。
    可用于SQL中的like场景。

    查询数组数组中每一个元素都是整个键的值。如有文档:
    文档1:{"fruit":["apple", "pear", "peach"]}, 文档2:{"fruit":["peach", "banana", "apple"]}, 文档3:{"fruit":["orange", "banana", "apple"]},
  • 单个元素匹配
    若查询文档为:{"fruit":"apple"},文档1,2,3都会被成功匹配。
  • 多个元素匹配
    需要用到$all条件句了,若查询文档为:{"fruit":{"$all":["apple","peach"]}},则文档1,2会被匹配,与元素顺序无关。
  • 精确匹配
    若查询文档为:{"fruit":["apple", "pear", "peach"]},则只匹配文档1,对于缺少或冗余,以及顺序不一致的都不会匹配到。
  • 下标匹配
    采用key.index方式,数组下标从0开始。如查询文档:{"fruit.2":"apple"},则文档2,3被匹配。
  • 长度匹配
    若查询文档为:{"fruit":{"$size":3}},表示查询长度为3的数组,文档1,2,3都会被匹配。
  • 内嵌文档的查询
  • 点表示法
    如文档:
    { "_id":1, "name":{"first":"Joe", "last":"Smith"} }
    则可以这样查询:{"name.first":"Joe", "name.last":"Smith"}
  • $elemMatch
    当需要对一个内嵌文档的多个键操作时使用。
    如有文档:
    { "comments": [ { "name": "Tom", "score": 3, "comment": "bad" }, { "name": "Jim", "score": 6, "comment": "good" } ] }
    要查找Tom评分大于5的评论文档,只能这样: {"comments":{"$elemMatch":{"name":"Tom","score":{"$gt":5}}}}
    而不能: {"comments":{"name":"Tom","score":{"$gt":5}}},不能匹配"comment"键了。
    或 {"comments.name":"Tom","comments.score":{"$gt":5}},匹配的不是同一条评论了。
  • linux

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

    MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

    MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

    MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

    Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

    MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

    Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

    It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

    What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

    Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

    How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

    Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

    MySQL: A User-Friendly Introduction to Databases MySQL: A User-Friendly Introduction to Databases Apr 10, 2025 am 09:27 AM

    The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

    MongoDB and relational database: a comprehensive comparison MongoDB and relational database: a comprehensive comparison Apr 08, 2025 pm 06:30 PM

    MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

    See all articles