Mongo DB:如何选择嵌套数组计数> 0的项目

1gn*_*ter 7 mongodb mongodb-.net-driver

该数据库接近5GB.我有这样的文件:

{
    _id: ..
    user: "a"
    hobbies: [{
        _id: ..
        name: football
    },
    {
        _id: ..
        name: beer
    }
    ...
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想要回复那些拥有超过0个"兴趣爱好"的用户

db.collection.find({"hobbies" : { &gt : 0}}).limit(10)
Run Code Online (Sandbox Code Playgroud)

它需要所有RAM而没有结果.

  1. 怎么做这个选择?
  2. 以及如何返回:id,name,count?
  3. 怎么用c#官方驱动程序呢?

TIA

PS 附近我发现:"为汉德类别大小添加新字段.这是mongo世界的惯常做法." 这是真的?

Par*_*ker 16

在这种特定情况下,您可以使用列表索引来解决您的问题:

db.collection.find({"hobbies.0" : {$exists : true}}).limit(10)

这只是确保存在第0个元素.您可以通过检查范围末端的现有元素来确保列表长度小于n或长度介于x和y之间.


Ram*_*Vel 8

你尝试过使用过吗hobbies.length?我没有测试过这个,但我相信这是查询mongodb中数组范围的正确方法

db.collection.find({$where: '(this.hobbies.length > 0)'})
Run Code Online (Sandbox Code Playgroud)


jay*_*elm 7

你可以(运行)$size使用逻辑检查一系列数组长度$not:

db.collection.find({array: {$not: {$size: 0}}})
Run Code Online (Sandbox Code Playgroud)