云开发,如何获取数据库中的某个数组字段包含某个值的数据总条数呢?
发布于 7 年前 作者 yeping 2324 次浏览 来自 官方Issues

假如数据库某集合中有以下三条数据:

    {

    {id:1,tags:[‘小明’,‘小红’,‘小芳’},

    {id:2,tags:[‘小明’,‘小菲’,‘小李’},

    {id:3,tags:[‘小明’,‘小紫’,‘小芳’},

    }    

我该如何获取,集合中含有’小芳’的tags数据的总条数?

3 回复
db.collection('products')
  .aggregate()
  .unwind('$tags')
  .match({
    tags: '小芳'
  })
  .count()
  .end()
  .then(console.log)

聚合应该可以做到,以上未测试。参考:

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/aggregation/aggregation.html

除了聚合,下面可能也是可以的:试试。

db.collection().where({tags:‘小芳’}).count()

回到顶部