![](/img/trans.png)
[英]Excel VBA loop through 10,000 sets of rows, each set containing 20 rows
[英]MongoDB query response is really slow, when searching for a phone number through 2 documents with each having 10,000 phone numbers
当前 MongoDB 查询,最多需要 5 分钟来搜索 2 个文档,当每个文档有 10,000 个联系人时,请提出显着改善这一点的方法。
我正在尝试在数百个文档中搜索电话号码。 每个文档属于一个用户,每个用户都有一个包含 10,000 个对象的联系人数组(如下面的代码所示),每个 object 可以有 2 到 3 个电话号码。 (参见下面的文档结构)。 如果在多个文档中找到电话号码,我需要 MongoDB 查询返回一个数组,其中包含在这些文档中找到的 userNumber。
下面是我在 MongoDB 集合中拥有的文档的结构。 为简单起见,我在contacts数组中只展示了一个object,实际上有数千个对象
{
"_id": { "$oid": "61d1f04266289f003452d705" },
"userID": { "$oid": "61d1efea2c0fab00340f47c8" },
"contacts": [
{
"emailAddresses": [
{ "id": "6884", "label": "email1", "email": "addedemail@gmail.com" }
],
"phoneNumbers": [
{
"label": "other",
"id": "4594",
"number": "+918984292930"
},
{
"label": "other",
"id": "4595",
"number": "+911234567890"
}
],
"_id": { "$oid": "61d1f04266289f003452d744" },
"ContactName": "Sample User 1 Name Changed",
"ContactNumber": "+918984292930",
"recordID": "833"
}
],
"userNumber": "+911234567890",
"__v": 7
}
当前 MongoDB 查询:
await ContactModel.aggregate([
{
$match: {
userNumber: userNumber,
},
},
{
$unwind: "$contacts",
},
{
$lookup: {
from: "phonenumbers",
let: {
contactNumberVar: "$contacts.ContactNumber",
},
pipeline: [
{ $unwind: "$contacts" },
{
$project: {
userNumber: 1,
"contacts.ContactNumber": 1,
},
},
{
$match: {
$and: [
{ $expr: { $eq: ["$$contactNumberVar", "$userNumber"] } },
{
$expr: {
$eq: [contactNumber, "$contacts.ContactNumber"],
},
},
],
},
},
],
as: "mutualContacts",
},
},
{
$project: {
userID: 1,
"mutualContacts.userNumber": 1,
},
},
{
$group: {
_id: "$userID",
mutualContacts: {
$push: {
$cond: [
{ $gt: [{ $size: "$mutualContacts" }, 0] },
{ $arrayElemAt: ["$mutualContacts.userNumber", 0] },
"$$REMOVE",
],
},
},
},
},
]).exec()
首先确保您的索引支持 collections 上的查询。
{userNumber:1}
应该是一个不错的候选人,但请测试其他选项。
下一步 - 查询优化。 在查找管道中:
pipeline: [
{ $unwind: "$contacts" },
{
$project: {
userNumber: 1,
"contacts.ContactNumber": 1,
},
},
{
$match: {
$and: [
{ $expr: { $eq: ["$$contactNumberVar", "$userNumber"] } },
{
$expr: {
$eq: [contactNumber, "$contacts.ContactNumber"],
},
},
],
},
},
],
您展开整个phonenumbers
集合。 首先匹配它,然后展开/项目仅匹配文档:
pipeline: [
{
$match: {
$and: [
{ $expr: { $eq: ["$$contactNumberVar", "$userNumber"] } },
{
$expr: {
$eq: [contactNumber, "$contacts.ContactNumber"],
},
},
],
},
},
{ $unwind: "$contacts" },
{
$project: {
userNumber: 1,
"contacts.ContactNumber": 1,
},
},
{
$match: {
$and: [
{ $expr: { $eq: ["$$contactNumberVar", "$userNumber"] } },
{
$expr: {
$eq: [contactNumber, "$contacts.ContactNumber"],
},
},
],
},
},
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.