【问题标题】:how to count number of sub object (same document) in mongodb [duplicate]如何计算mongodb中子对象(同一文档)的数量[重复]
【发布时间】:2015-08-26 09:30:22
【问题描述】:

示例文档:

{
    "aliases" : {
        "name" : [ 
            "Brinton McKay", 
            "Dr. Theopolis", 
            "Galactic Spiral Sound", 
            "Highrise", 
            "Memory Boy", 
            "Semblance Factor", 
            "Spy (2)", 
            "Three O'Clock High"]}
}

如何计算“别名”下的“名称”数量? 我想打印所有包含 3 个以上别名的 _id。 任何帮助将不胜感激。

【问题讨论】:

  • 看看this answer。
  • 所以在这种情况下它将是:db.coll.find({'aliases.name.3': {$exists: true}})

标签: mongodb mongodb-query


【解决方案1】:

请检查以下查询:

db.collection.find({ $where : function() 
{ return Object.keys(this.aliases.name).length > 3 } });

或

db.collection.aggregate([
{$project : { _id :1 , numb : {$size : "$aliases.name"} }
},
{$match : { numb :{$gt : 3 }}
}
]);

PS:您可以在以下链接中查看文档: http://docs.mongodb.org/manual/reference/operator/query/where/

【讨论】:

  • 这是错误:error: { "$err" : "Can't canonicalize query: BadValue $size needs a number", "code" : 17287 }
  • 你能检查一下上面的查询吗?
  • 它有效,但作为 { $size: 3 } 而不是 {$size:{$gt:3}} ,我如何使用 $gt?非常感谢
  • 我已经使用聚合函数发布了另一个查询,您也可以检查一下。我已经在我的帖子中编辑了它。请尝试一下。
  • 这个很完美:db.coll.find({'aliases.name.3': {$exists: true}}) 很棒的 JohnnyHK 和 Yathish。你们很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多