Mongo-对象键可变的地方匹配 [英] Mongo - Match where object key is variable
问题描述
我有一个具有以下对象的Mongo数据库:
I have a Mongo DB with the following object:
[
{
"link" : "xxxxx.jpg"
"_id" : ObjectId("5501b1648ef0b4eccc41814e"),
"processed" : {
"320" : true,
"480" : true,
"540" : true,
"720" : true,
"800" : true,
"1080" : true,
"original" : false,
"iPhone" : true
}
}
]
我正在尝试查询任何已处理的值是否为假的位置,但是我似乎无法弄清楚如何查询不知道哪个键匹配的位置.是否可以不循环浏览所有文档?
I am trying to query where any of the processed values is false, but I cannot seem to figure out how to query where I do not know which key matches. Is this possible without looping through all documents?
推荐答案
有了像您在原始文章中一样的文档架构,我们可以使用Javascript来实现
With a document schema like you've put in the original post, we can use Javascript to;
- 查找所有记录
- 通过
processed
对象循环 - 如果 any 值等于布尔值
false
,则将_id
添加到数组中 - 打印在
processed
对象中具有false
值的_id
.
- Find all records
- Loop through
processed
object - If any value equates to boolean
false
, add the_id
to an array - Print the
_id
's that have afalse
value inprocessed
object
要运行的查询
var arrDoc = [];
db.test.find().forEach(
function anyFalse(doc) {
for(key in doc.processed) {
if(doc.processed.hasOwnProperty(key) && doc.processed[key] === false) {
arrDoc.push(doc._id);
break;
}
}
});
print( arrDoc.join("\r\n") );
示例文档
{
"_id" : ObjectId("5107de525ed6103609000016"),
"link" : "xxxxx.jpg",
"processed" : {
"320" : true,
"480" : true,
"540" : true,
"720" : true,
"800" : true,
"1080" : true,
"original" : false,
"iPhone" : true
}
}
示例输出
ObjectId("5107de525ed6103609000016")
更多笔记
您可以将此JavaScript函数anyFalse
存储到Mongo中,并在需要时调用它.请参见在服务器上存储javascript函数
You can store this javascript function anyFalse
into Mongo and call it when you need it. See store javascript function on server
如注释中所述,您有一个images
数组.此函数将遍历所有images
数组以检查子级processed
是否为假.
As noted in the comments, you have an images
array. This function will loop through all the images
array to check child processed
for false.
要运行的查询
var arrDoc = [];
db.test.find().forEach(
function anyFalse(doc) {
var len = doc.images.length;
for( var i = 0; i < len; i++ ) {
for(key in doc.images[i].processed) {
if(doc.images[i].processed.hasOwnProperty(key) && doc.images[i].processed[key] === false) {
arrDoc.push(doc.images[i]._id);
break;
}
}
}
});
print( arrDoc.join("\r\n") );
示例文档
{
"_id" : ObjectId("5534fe2f3614af9afd23310a"),
"images" : [
{
"_id" : ObjectId("5107de525ed6103609000016"),
"link" : "xxxxx.jpg",
"processed" : {
"320" : true,
"480" : true,
"540" : true,
"720" : true,
"800" : true,
"1080" : true,
"original" : true,
"iPhone" : true
}
},
{
"_id" : ObjectId("5107de525ed6103609000017"),
"link" : "xxxxx.jpg",
"processed" : {
"320" : true,
"480" : true,
"540" : true,
"720" : true,
"800" : true,
"1080" : true,
"original" : false,
"iPhone" : true
}
}
]
}
这篇关于Mongo-对象键可变的地方匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!