mongodb 访问子文档 [英] mongodb accessing subdocuments
问题描述
我有一个与下面提到的非常相似的集合(用户).
I have a collection (users) which looks very much the same as mentioned below.
db.users.find().pretty();
{
"_id" : ObjectId("5773fc2826e0b6cf532569ca"),
"user" : {
"login" : "tester"
}
}
{
"_id" : ObjectId("5773fd6426e0b6cf532569cb"),
"user" : {
"login" : "tester",
"name" : "anil"
}
}
当我这样做
> db.users.find({"user":{"login":"tester"}});
我得到了这个结果
{ "_id" : ObjectId("5773fc2826e0b6cf532569ca"), "user" : { "login" : "tester" } }
但是当我在下面做时,我没有得到任何记录.
However when I do below, I get no records.
db.users.find({"user":{"name":"anil"}});
>所以我的问题是为什么第二个查询没有返回响应?
> so my question is why does the second query returns no response ?
另外,根据上面的例子,我什至怀疑这是否是访问子文档的正确方法?
Also, based on the examples above, I am even doubting if this is the correct way to access subdocuments ?
不应该通过 .notation 访问子文档.像下面这样?(在这种情况下,我在两种情况下都得到了正确的输出)
Shouldn't the subdocuments be accessed via .notation. Something like below ? (in which case I get the correct output in both the cases)
db.users.find({"user.login":"tester"});
{ "_id" : ObjectId("5773fc2826e0b6cf532569ca"), "user" : { "login" : "tester" } }
{ "_id" : ObjectId("5773fd6426e0b6cf532569cb"), "user" : { "login" : "tester", "name" : "anil" } }
和
> db.users.find({"user.name":"anil"});
{ "_id" : ObjectId("5773fd6426e0b6cf532569cb"), "user" : { "login" : "tester", "name" : "anil" } }
>
推荐答案
另外,根据上面的例子,我什至怀疑这是否是访问子文档的正确方法?
Also, based on the examples above, I am even doubting if this is the correct way to access subdocuments ?
这实际上不是.第一个查询,db.users.find({"user":{"login":"tester"}});
,意味着你正在寻找一个user
完全等于 {"login":"tester"}
对象,而不是具有 login
字段的用户等于 tester
.有一个文档与该条件匹配,并且该文档实际作为查询结果返回.
This is not actually. The first query, db.users.find({"user":{"login":"tester"}});
, means that you're looking for a user
that equals to {"login":"tester"}
object completely, not a user with login
field equals to tester
. There is one document that matches with that criteria and that document actually returned as the query result.
同样,第二个查询 db.users.find({"user":{"name":"anil"}});
表示您正在寻找一个 user
完全等于 {"name":"anil"}
对象.没有这样的user
.有一个文档与您的查询部分匹配,但这还不够.
Likewise, the second query, db.users.find({"user":{"name":"anil"}});
, means that you're looking for a user
that equals to {"name":"anil"}
object completely. There is no such user
. There is one document that matches with your query partially but it's not enough.
如果您正在寻找 name
等于 anil
的 user
,请使用 Dot Notation 访问子文档,就像您在第二组查询中所做的那样.
If you're looking for a user
with name
equals to anil
, use Dot Notation to access the sub-document, as you did in your second group of queries.
不应该通过 .notation 访问子文档.就像是以下 ?(在这种情况下,我在两种情况下都得到了正确的输出)
Shouldn't the subdocuments be accessed via .notation. Something like below ? (in which case I get the correct output in both the cases)
是的.这是正确的方法.
Yes. this is the correct way.
这篇关于mongodb 访问子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!