[英]MongoDb - How to search BSON composite key exactly?
I have a collection that stored information about devices like the following: 我有一个存储有关以下设备信息的集合:
/* 1 */
{
"_id" : {
"startDate" : "2012-12-20",
"endDate" : "2012-12-30",
"dimensions" : ["manufacturer", "model"],
"metrics" : ["deviceCount"]
},
"data" : {
"results" : "1"
}
}
/* 2 */
{
"_id" : {
"startDate" : "2012-12-20",
"endDate" : "2012-12-30",
"dimensions" : ["manufacturer", "model"],
"metrics" : ["deviceCount", "noOfUsers"]
},
"data" : {
"results" : "2"
}
}
/* 3 */
{
"_id" : {
"dimensions" : ["manufacturer", "model"],
"metrics" : ["deviceCount", "noOfUsers"]
},
"data" : {
"results" : "3"
}
}
And I am trying to query the documents using the _id field which will be unique. 我正在尝试使用_id字段来查询文档,这将是唯一的。 The problem I am having is that when I query for all the different attributes as in: 我遇到的问题是,当我查询所有不同的属性时,如下所示:
db.collection.find({$and: [{"_id.dimensions":{ $all: ["manufacturer","model"], $size: 2}}, {"_id.metrics": { $all:["noOfUsers","deviceCount"], $size: 2}}]});
This matches 2 and 3 documents (I don't care about the order of the attributes values), but I would like to only get 3 back. 这匹配2个和3个文档(我不在乎属性值的顺序),但是我只想得到3个。 How can I say that there should not be any other attributes to _id than those that I specify in the search query? 我该怎么说_id应该没有除搜索查询中指定的那些其他属性?
Please advise. 请指教。 Thanks. 谢谢。
Unfortunately, I think the closest you can get to narrowing your query results to just unordered _id.dimensions
and unordered _id.metrics
requires you to know the other possible fields in the _id
subdocument field, eg. 不幸的是,我认为将查询结果范围缩小到无序_id.dimensions
和无序_id.metrics
_id.dimensions
, _id.metrics
需要您知道_id
子文档字段中的其他可能字段。 startDate
and endDate
. startDate
和endDate
。
db.collection.find({$and: [
{"_id.dimensions":{ $all: ["manufacturer","model"], $size: 2}},
{"_id.metrics": { $all:["noOfUsers","deviceCount"], $size: 2}},
{"_id.startDate":{$exists:false}},
{"_id.endDate":{$exists:false}}
]});
If you don't know the set of possible fields in _id
, then the other possible solution would be to specify the exact _id
that you want, eg. 如果您不知道_id
中可能的字段集,那么另一种可能的解决方案是指定所需的确切_id
,例如。
db.collection.find({"_id" : {
"dimensions" : ["manufacturer", "model"],
"metrics" : ["deviceCount", "noOfUsers"]
}})
but this means that the order of _id.dimensions
and _id.metrics
is significant. 但这意味着_id.dimensions
和_id.metrics
的顺序很重要。 This last query does a document match on exact BSON representation of _id
. 最后一个查询在_id
确切BSON表示形式上进行了文档匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.