Arrays 在MongoDB中查找其数组字段包含某些子集的文档
“用户”集合中的文档具有数组字段 示例文件:Arrays 在MongoDB中查找其数组字段包含某些子集的文档,arrays,mongodb,Arrays,Mongodb,“用户”集合中的文档具有数组字段 示例文件: { "_id" :1001, "properties" : ["A", "B", "C", "D", "E", "F", "G", "H", "I"] } { "_id" : 1002, "properties" : ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] } 如何构建查询以获取符合下一个条件的文档? 仅获取具有以下属性的文档: [ "3" AND ("
{
"_id" :1001,
"properties" : ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
}
{
"_id" : 1002,
"properties" : ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
}
如何构建查询以获取符合下一个条件的文档?
仅获取具有以下属性的文档:
[ "3" AND ("A" OR "1") AND ("B" OR "2") ]
或者以其他方式:
"3" AND "A" AND "B"
OR
"3" AND "A" AND "2"
OR
"3" AND "1" AND "B"
OR
"3" AND "1" AND "2"
在上一个示例中,查询只能生成文档:
{
"_id" : 1002,
"properties" : ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
}
该收藏有400万份文件。文档数组“属性”字段的平均长度为15个元素。我要查找的查询在这个相当大的集合中必须具有良好的性能。尝试以下方法:
db.users.find(
{
$or: [
{$and: [{ "properties": "3" }, { "properties": "A" }, { "properties": "B" }]},
{$and: [{ "properties": "3" }, { "properties": "A" }, { "properties": "2" }]},
{$and: [{ "properties": "3" }, { "properties": "1" }, { "properties": "B" }]},
{$and: [{ "properties": "3" }, { "properties": "1" }, { "properties": "2" }]}
]
}
);
或
斯蒂芬的回答是可以的。使用和操作员实现结果的其他方法:
db.users.find(
{
$and:[
{"properties":"3"},
{"properties" : {$in: ["A", "1"]}},
{"properties" : {$in: ["B", "2"]}}
]
}
);
(您对子集的第一次描述的翻译)
及
(翻译您对子集的第二次描述)
恐怕我说不出哪一个能保证最好的性能。我希望您在属性
上拥有和索引
您可以尝试对较小的集合进行查询,以查看执行计划
db.users.find(
{
$and:[
{"properties":"3"},
{"properties" : {$in: ["A", "1"]}},
{"properties" : {$in: ["B", "2"]}}
]
}
);
db.users.find(
{
$or: [
{"properties" : {$all: ["3", "A", "B"]}},
{"properties" : {$all: ["3", "A", "2"]}},
{"properties" : {$all: ["3", "1", "B"]}},
{"properties" : {$all: ["3", "1", "2"]}}
]
}
);