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" : "[email protected]", 8 "content" : "good blog" 9 }, 10 { 11 "content" : "Changed Comment", 12 "email" : "[email protected]", 13 "name" : "john" 14 }, 15 { 16 "name" : "test", 17 "email" : "[email protected]", 18 "content" : "test" 19 }, 20 { 21 "name" : "test1", 22 "email" : "[email protected]", 23 "content" : "test1" 24 }, 25 { 26 "name" : "test12", 27 "email" : "[email protected]", 28 "content" : "test12" 29 }, 30 { 31 "name" : "test123", 32 "email" : "[email protected]", 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“,将限定条件进行分组,仅当需要对一个内嵌文档的多个键操作时会用到

你可能感兴趣的:(mongodb)