zoukankan      html  css  js  c++  java
  • mongodb内嵌文档的查询

    本文转自:http://blog.163.com/wm_at163/blog/static/1321734902012526103825481/
    1
    > db.blog.findOne() 2 { 3 “_id” : ObjectId(“4e914ad2717ed94f8289ac08″), 4 “comments” : [ 5 { 6 "name" : "joe", 7 "email" : "joe@example.com", 8 "content" : "good blog" 9 }, 10 { 11 "content" : "Changed Comment", 12 "email" : "john@gmail.com", 13 "name" : "john" 14 }, 15 { 16 "name" : "test", 17 "email" : "test@test.com", 18 "content" : "test" 19 }, 20 { 21 "name" : "test1", 22 "email" : "test1@test.com", 23 "content" : "test1" 24 }, 25 { 26 "name" : "test12", 27 "email" : "test12@test.com", 28 "content" : "test12" 29 }, 30 { 31 "name" : "test123", 32 "email" : "test123@test.com", 33 "content" : "test123" 34 } 35 ], 36 “content” : “My first blog.”, 37 “title” : “Hello World” 38 }

    一般来说,使用点连接来查询内嵌文档,查询语句如下:

    >  db.blog.find({“comments.name”:”test”}) 

    我们需要查询评论作者为”test”,内容为”test1″的博客,使用这种查询db.blog.find({“comments.name”:”test”,”comments.content”:”test1″})是不会达到目的的,因为符合作者是test和内容是test1的评论可能不是同一条评论,但出现在同一篇博客里,所以这样的博客也会被返回。正确的查询语句应该是这样写的:

    >  db.blog.find({“$elemMatch”:{“comments.name”:”test”,”comments.content”:”test1″}})

    使用了”$elemMatch“,将限定条件进行分组,仅当需要对一个内嵌文档的多个键操作时会用到
  • 相关阅读:
    浮窗显示到毫秒时间的小工具 各大电商平台的时间
    非常不错的电脑截图软件介绍—截图加贴图。
    ​Everything 文件搜索神器 基于名称实时定位文件和目录
    THUPC2021初赛 & ICPC上海站游记
    旧题重做
    常用思想方法——数学期望篇
    vim 常用操作技巧
    生物制图软件——CirCos在Linux服务器上安装步骤:
    vue-element-admin 改造
    vue
  • 原文地址:https://www.cnblogs.com/laifu/p/3633006.html
Copyright © 2011-2022 走看看