search
HomeDatabaseMysql TutorialMongoDB基本查询整理

精确匹配 单个键值对:{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
    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
    How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

    MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

    MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

    The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

    Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

    MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

    SQL Commands in MySQL: Practical ExamplesSQL Commands in MySQL: Practical ExamplesApr 14, 2025 am 12:09 AM

    SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

    How does InnoDB handle ACID compliance?How does InnoDB handle ACID compliance?Apr 14, 2025 am 12:03 AM

    InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

    MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

    MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

    MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

    MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

    What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

    InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

    See all articles

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft