在mongodb中仅获得10位手机号码?

时间:2018-09-24 10:10:33

标签: mongodb nosql aggregation-framework

我有一个名为个人资料的收藏集,如下所示。

{
name :"abc",
mobile : 9876543210
},
{
name :"def",
mobile : 98454
},
{
name :"ghi",
mobile : 1234567890
},
{
name :"mno",
mobile : 125456
}

现在,我希望输出为

{
name :"abc",
mobile : 9876543210
},

{
name :"ghi",
mobile : 1234567890
}

我已经尝试过了,但是它仅适用于字符串字段。

db.profile.find( { $where: "this.mobile.length = 10" } );

有帮助吗?

1 个答案:

答案 0 :(得分:1)

您可以在mongodb 3.6 及更高版本

中尝试以下聚合

您可以使用$strLenCP聚合检查字符串的长度,然后过滤字符串长度等于**10**的文档

db.collection.aggregate([
  { "$match": {
    "$expr": {
      "$eq": [{ "$strLenCP": { "$toLower": "$mobile" }}, 11]
    }
  }}
])

甚至使用查找查询

db.collection.find({
  "$expr": {
    "$eq": [{ "$strLenCP": { "$toLower": "$mobile" }}, 11]
  }
})

对于 3.6

之前的mongodb版本
db.collection.aggregate([
  { "$addFields": {
    "mobileLength": {
      "$strLenCP": { "$toLower": "$mobile" }
    }
  }},
  { "$match": { "mobileLength": 11 }},
  { "$project": { "mobileLength": 0 }}
])