您的位置:首页 > 数据库 > Mongodb

mongodb内嵌文档的查询

2014-03-29 20:09 281 查看
本文转自:http://blog.163.com/wm_at163/blog/static/1321734902012526103825481/
1 > db.blog.findOne()
{
“_id” : ObjectId(“4e914ad2717ed94f8289ac08″),
“comments” : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "good blog"
},
{
"content" : "Changed Comment",
"email" : "john@gmail.com",
"name" : "john"
},
{
"name" : "test",
"email" : "test@test.com",
"content" : "test"
},
{
"name" : "test1",
"email" : "test1@test.com",
"content" : "test1"
},
{
"name" : "test12",
"email" : "test12@test.com",
"content" : "test12"
},
{
"name" : "test123",
"email" : "test123@test.com",
"content" : "test123"
}
],
“content” : “My first blog.”,
“title” : “Hello World”
}


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

> 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“,将限定条件进行分组,仅当需要对一个内嵌文档的多个键操作时会用到
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: