MongoDB 查询文档

    pretty() 方法

    结果显示在一个格式化的方式,可以使用 pretty() 方法.

    语法:

    例子

    1. > db.mycol.find().pretty()
    2. {
    3. "_id" : ObjectId("5799c3eb235910620b89c674"),
    4. "title" : "MongoDB Overview",
    5. "description" : "MongoDB is no sql database",
    6. "by" : "tutorials itcast",
    7. "url" : "http://www.itcast.cn",
    8. "tags" : [
    9. "mongodb",
    10. "database",
    11. "NoSQL"
    12. ],
    13. "likes" : 100
    14. }
    15. {
    16. "_id" : ObjectId("5799c3f3235910620b89c675"),
    17. "title" : "MySQL Overview",
    18. "description" : "MySQL is sql database",
    19. "by" : "tutorials itcast",
    20. "url" : "http://www.itcast.cn",
    21. "tags" : [
    22. "MySQL",
    23. "database",
    24. "SQL"
    25. ],
    26. "likes" : 40
    27. >

    MongoDB 与 RDBMS Where 语句比较

    AND 在MongoDB中用法

    语法:

    在 find() 方法,如果通过多个键分离',',那么 MongoDB 处理 AND 条件。AND 基本语法如下所示:

    1. >db.mycol.find({key1:value1, key2:value2}).pretty()

    例子

    下面给出的例子将显示所有的教程,标题是“MongoDB Overview“

    1. > db.mycol.find({"by":"tutorials itcast","title": "MongoDB Overview"}).pretty()
    2. {
    3. "_id" : ObjectId("5799c3eb235910620b89c674"),
    4. "title" : "MongoDB Overview",
    5. "description" : "MongoDB is no sql database",
    6. "by" : "tutorials itcast",
    7. "url" : "http://www.itcast.cn",
    8. "mongodb",
    9. "database",
    10. "NoSQL"
    11. ],
    12. "likes" : 100
    13. }
    14. >

    MongoDB中OR

    语法:

    OR条件的基础上要查询文件,需要使用$or关键字。OR 基本语法如下所示:

    例子

    下面给出的例子将显示所有的教程,标题是“MongoDB Overview'或'MySQL Overview'

    1. >db.mycol.find({
    2. $or: [
    3. {
    4. "title": "MySQL Overview"
    5. },
    6. {
    7. "title": "MongoDB Overview"
    8. }
    9. ]
    10. }).pretty()
    11. {
    12. "_id" : ObjectId("57cefded600d5bb1e2acdb70"),
    13. "title" : "MongoDB Overview",
    14. "description" : "MongoDB is no sql database",
    15. "by" : "tutorials itcast",
    16. "url" : "http://www.itcast.cn",
    17. "tags" : [
    18. "mongodb",
    19. "database",
    20. "NoSQL"
    21. ],
    22. "likes" : 100
    23. {
    24. "_id" : ObjectId("57cefdf7600d5bb1e2acdb71"),
    25. "title" : "MySQL Overview",
    26. "description" : "MySQL is sql database",
    27. "by" : "tutorials itcast",
    28. "tags" : [
    29. "MySQL",
    30. "database",
    31. "SQL"
    32. ],
    33. "likes" : 40
    34. }
    35. >

    AND 和 OR 一起使用

    例子

    1. > db.mycol.find({
    2. "likes": {
    3. $gt: 50
    4. },
    5. $or: [
    6. {
    7. "by": "tutorials itcast"
    8. },
    9. {
    10. "title": "MongoDB Overview"
    11. }
    12. ]
    13. }).pretty()
    14. {
    15. "_id" : ObjectId("57cefded600d5bb1e2acdb70"),
    16. "title" : "MongoDB Overview",
    17. "description" : "MongoDB is no sql database",
    18. "by" : "tutorials itcast",
    19. "url" : "http://www.itcast.cn",
    20. "tags" : [
    21. "mongodb",
    22. "database",
    23. "NoSQL"
    24. ],
    25. "likes" : 100
    26. >