MongoDB-查找匹配未知字段键的某些条件的文档 [英] MongoDB - Find documents matching certain condition for unknown field keys
问题描述
如何查询MongoDB集合以查找具有以下结构的文档?这些文档有一个名为 thing
的字段,它是一个子文档,并且此字段的键是一种ID号的形式,编写查询的人通常会不知道(使点表示法困难,我认为这是不可能的.)
How can I query a MongoDB collection to find documents with a structure as below? The documents have a field called thing
which is a subdocument, and the keys for this field are a form of ID number which will generally not be known by the person writing the query (making dot notation difficult and I assume impossible).
{
"_id" : 3,
"_id2" : 234,
"thing":
{
"2340945683":
{"attribute1": "typeA",
"attribute2": "typeB",
"attribute3": "typeA"
},
"349687346":
{"attribute1": "typeC",
"attribute2": "typeB",
"attribute3": "typeA"
}
},
"username": "user1"
}
说我想设置一个过滤器,该过滤器仅在 thing
中的某个或多个字段具有条件"attribute1":"typeC"
时才返回文档?
Say I want to set a filter which will return the document only if some one or more of the fields within thing
have the condition "attribute1" : "typeC"
?
我需要
db.collection.find( {thing.ANY_FIELD: $elemMatch:{"attribute1":"typeC"}})
推荐答案
您需要从 $ map 属性和 {"attribute1":"typeC"}
:
You need to start with $objectToArray to read your keys dynamically. Then you can $map properties along with $anyElementTrue to detect if there's any nested field in thing
containing {"attribute1":"typeC"}
:
db.collection.aggregate([
{
$match: {
$expr: {
$anyElementTrue: {
$map: {
input: { $objectToArray: "$thing" },
in: { $eq: [ "$$this.v.attribute1", "typeC" ] }
}
}
}
}
}
])
这篇关于MongoDB-查找匹配未知字段键的某些条件的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!