猫鼬:查找具有多个条目的混合模式类型文档 [英] Mongoose: find mixed schema type documents with multiple entries
问题描述
我的数据模型大致如下:
My data model looks roughly like this:
data = {
...
parameters: [{type:Schema.Types.mixed}],
...
}
如果我现在将文档插入数据库,
If i now insert a document into the database,
doc = {
...
parameters:[{"foo":"bar"}],
...
}
我可以通过参数"键进行查询:
i can query it via the "parameters" key:
db.dataset.find({"parameters":[{"foo":"bar"}]},function(doc){
...
})
并取回预期的文档.但是,如果参数"包含多个键,例如
and get back the expected document. However if "parameters" contains more than one key, for example
doc = {
...
parameters:[{"foo":"bar","ding":"dong"}]
...
}
我找不到它了.为什么?
i cant find it anymore. Why?
推荐答案
这是因为查询无法匹配数组字段parameters
具有确切的数组对象作为其值[{"foo": "bar", "ding": "dong"}]
的任何文档.为了说明这一点,让我们在集合中插入几个示例文档:
It is because the query cannot match any documents where the array field parameters
has the exact array object as its value [{"foo": "bar", "ding": "dong"}]
. To demonstrate this, let's insert a couple of sample documents in a collection:
/* 0 */
{
"_id" : ObjectId("551d777fcfd33f4e2a61e48f"),
"parameters" : [
{
"foo" : "bar"
}
]
}
/* 1 */
{
"_id" : ObjectId("551d777fcfd33f4e2a61e490"),
"parameters" : [
{
"foo" : "bar",
"ding" : "dong"
}
]
}
使用该对象数组[{"foo":"bar"}]
在此集合中查询parameters
数组,将带"_id"的文档出现:ObjectId("551d777fcfd33f4e2a61e48f")
.但是,如果将查询对象更改为使用 $elemMatch
,那么它将同时带来两个文档:
Querying this collection for parameters
array with this object array [{"foo":"bar"}]
will bring the document with "_id" : ObjectId("551d777fcfd33f4e2a61e48f")
. However, if you change your query object to use $elemMatch
then it will bring both documents:
db.collection.find({"parameters": { "$elemMatch": { "foo": "bar" } }});
这篇关于猫鼬:查找具有多个条目的混合模式类型文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!