Arrays 写一个mongo查询来计算数组中相似数据所在的数据?
样本数据:有多个类似的集合:Arrays 写一个mongo查询来计算数组中相似数据所在的数据?,arrays,mongodb,object,mongodb-query,mongo-collection,Arrays,Mongodb,Object,Mongodb Query,Mongo Collection,样本数据:有多个类似的集合: { "_id" : NumberLong(301), "telecom" : [ { "countryCode" : { "value" : "+1" }, "extension" : [
{
"_id" : NumberLong(301),
"telecom" : [
{
"countryCode" : {
"value" : "+1"
},
"extension" : [
{
"url" : "primary",
"value" : [
"true"
]
}
],
"modifiedValue" : {
"value" : "8887778888"
},
"system" : {
"value" : "phone"
},
"useCode" : {
"value" : "Home Phone"
},
"value" : {
"value" : "8887778888"
}
},
{
"extension" : [
{
"url" : "primary",
"value" : [
"true"
]
}
],
"modifiedValue" : {
"value" : "abc@test.com"
},
"system" : {
"value" : "email"
},
"useCode" : {
"value" : "work"
},
"value" : {
"value" : "abc@test.com"
}
}
]
}
问题:我想继续收集邮件,其中电子邮件部分对象中不存在telecom.system.value=email
和countryCode
。这里我附加了一个脚本,但我需要一行查询
var count = 0,i;
db.getCollection('practitioner').find({"telecom.system.value":"email"}).forEach(function(practitioner){
//print("updating : " +practitioner._id.valueOf())
telecom = practitioner.telecom.valueOf()
for(i= 0;i<telecom.length;i++){
if(telecom[i].system.value === 'email' && telecom[i].countryCode){
count+=1;
}
}
});
print(" Total count of the practitioner with country code in email object: "+count)
var计数=0,i;
db.getCollection('practices').find({“telecom.system.value”:“email”}).forEach(函数(practices){
//打印(“更新:+从业者.\u id.valueOf())
telecom=从业者.telecom.valueOf()
对于(i=0;i您可以尝试聚合方法aggregate()
方法1:
countryCode
的$match
条件应该存在,并且系统值应该是email
$filter
要迭代telecom
数组的循环并检查这两个条件,这将返回预期的元素
$size
从上述筛选结果中获取总元素
$group
按空值和总计计数
方法2:
countryCode
的$match
条件应该存在,并且系统值应该是email
$unwind
解构电信
阵列
$match
使用上述条件筛选文档
$count
获取元素总数
我没有测试性能,但您可以根据您的要求进行检查和使用
提供的答案中是否有您认为无法解决您的问题的内容?如果是,请对答案进行评论,以澄清哪些内容确实需要解决,但没有解决。如果答案确实回答了您提出的问题,请注意您提出的问题
var result = await db.getCollection('practitioner').aggregate([
{
$match: {
telecom: {
$elemMatch: {
countryCode: { $exists: true },
"system.value": "email"
}
}
}
},
{
$project: {
count: {
$size: {
$filter: {
input: "$telecom",
cond: {
$and: [
{ $ne: [{ $type: "$$this.countryCode" }, "missing"] },
{ $eq: ["$$this.system.value", "email"] }
]
}
}
}
}
}
},
{
$group: {
_id: null,
count: { $sum: "$count" }
}
}
]);
print("Total count of the practitioner with country code in email object: "+result[0].count);
var result = await db.getCollection('practitioner').aggregate([
{
$match: {
telecom: {
$elemMatch: {
countryCode: { $exists: true },
"system.value": "email"
}
}
}
},
{ $unwind: "$telecom" },
{
$match: {
"telecom.countryCode": { $exists: true },
"telecom.system.value": "email"
}
},
{ $count: "count" }
]);
print("Total count of the practitioner with country code in email object: "+result[0].count);