我在集合中的几乎每个文档中都有一个名为 tags
的数组字段。有一些文档没有该字段。
如果我运行 db.posts.find({ "some_tag": { $in: Tags } });
我希望 MongoDB 只返回其中包含“some_tag”的帖子他们的 tag
字段,并排除那些甚至没有该字段的字段,但我实际上收到此错误:JavaScript执行失败:ReferenceError:miembros未定义
这是为什么呢?如果某些文档没有该字段,我可以通过这种方式查询我的集合吗?
编辑:问题已解决。请参阅第一条评论。
最佳答案
I'd expect MongoDB to return only the posts that do have "some_tag" in their tag
这就是它的作用,如果你正确查询的话:
> db.tags.insert({"name" : "john", "tags" : ["tag", "boo"]});
> db.tags.insert({"name" : "mike" });
> db.tags.find({"tags" : "boo" });
{ "_id" : ObjectId("525e53a5e90cc5362ea98842"),
"name" : "john", "tags" : [ "tag", "boo" ] }
或
> db.tags.find({"tags" : {$in : [ "boo"] } });
{ "_id" : ObjectId("525e53a5e90cc5362ea98842"),
"name" : "john", "tags" : [ "tag", "boo" ] }
问题是您颠倒了 $in
:您正在寻找“在其 tag
字段中确实有 'some_tag' 的帖子”,但是查询 { "some_tag": { $in: Tags } }
查找具有 field some_tag
且具有 中给定值之一的文档标签
。
关于javascript - 查询MongoDB中不存在的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398700/