假设我们在 mongodb 集合中有这样的对象:
{
_id: 00000001
colors: ["green", "yellow"],
houses: [
{
number: 1,
owner: "John"
},
{
number: 2,
owner: "John"
},
{
number:3,
owner: "Dave"
}
]
},
{
_id: 00000002
colors: ["green", "red"],
houses: [
{
number: 15,
owner: "Dave"
},
]
}
因此,要获取颜色数组包含绿色的每个对象,我需要编写的查询将如下所示:collection.find({colors: "green"});
现在,如果我想获取约翰拥有房屋的所有对象,我将如何制定这样的查询?
基本上我要问的是,如果我的查询是 collection.find({houses: {owner: "John", number: ?}})
我需要用什么来替换 "?"
来告诉 mongo 我不关心 number 有什么值。
或者也许还有另一种我没有想到的方法?
感谢您的任何帮助!
(顺便说一句,这是一个虚构的示例,因此 ID 看起来很奇怪,而且对象本身似乎不太有用。)
最佳答案
要查询对象数组,您可以使用 dot notation ,尝试:
db.collection.find({ "houses.owner": "John"}})
关于arrays - 忽略字段mongodb请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160064/