如何在 MongoDB 中打印数组元素的计数以及另一个变量

Posted

技术标签:

【中文标题】如何在 MongoDB 中打印数组元素的计数以及另一个变量【英文标题】:How to print the count of array elements along with another variable in MongoDB 【发布时间】:2019-09-25 02:31:44 【问题描述】:

我有一个数据集合,其中包含以下格式的记录。


    "_id": 22,
    "title": "Hibernate in Action",
    "isbn": "193239415X",
    "pageCount": 400,
    "publishedDate": ISODate("2004-08-01T07:00:00Z"),
    "thumbnailUrl": "https://s3.amazonaws.com/AKIAJC5RLADLUMVRPFDQ.book-thumb-images/bauer.jpg",
    "shortDescription": "\"2005 Best Java Book!\" -- Java Developer's Journal",
    "longDescription": "Hibernate practically exploded on the Java scene. Why is this open-source tool so popular  Because it automates a tedious task: persisting your Java objects to a relational database. The inevitable mismatch between your object-oriented code and the relational database requires you to write code that maps one to the other. This code is often complex, tedious and costly to develop. Hibernate does the mapping for you.    Not only that, Hibernate makes it easy. Positioned as a layer between your application and your database, Hibernate takes care of loading and saving of objects. Hibernate applications are cheaper, more portable, and more resilient to change. And they perform better than anything you are likely to develop yourself.    Hibernate in Action carefully explains the concepts you need, then gets you going. It builds on a single example to show you how to use Hibernate in practice, how to deal with concurrency and transactions, how to efficiently retrieve objects and use caching.    The authors created Hibernate and they field questions from the Hibernate community every day - they know how to make Hibernate sing. Knowledge and insight seep out of every pore of this book.",
    "status": "PUBLISH",
    "authors": ["Christian Bauer", "Gavin King"],
    "categories": ["Java"]

我想打印标题,作者数大于 4 的地方。 我使用以下命令来提取超过 4 个作者的记录。

db.books.find(authors:$exists:true,$where:'this.authors.length>4',_id:0,title:1);

但无法连同标题一起打印作者数量。我也尝试使用以下命令。但它只给出了标题列表。

db.books.find(authors:$exists:true,$where:'this.authors.length>4',_id:0,title:1,'this.authors.length':1);

你能帮我把作者的数量和标题一起打印出来吗?

【问题讨论】:

【参考方案1】:

您可以使用聚合框架的$project 和$size 来重塑您的数据,然后使用$match 来应用过滤条件:

db.collection.aggregate([
    
        $project: 
            title: 1,
            authorsCount:  $size: "$authors" 
        
    ,
    
        $match: 
            authorsCount:  $gt: 4 
        
    
])

Mongo Playground

【讨论】:

你也可以看看这个。 ***.com/q/56027966/7234570

以上是关于如何在 MongoDB 中打印数组元素的计数以及另一个变量的主要内容,如果未能解决你的问题,请参考以下文章

如何计算另一个数组 MongoDB 中数组中的匹配元素

MongoDB计数按数组元素分组的数组中的匹配字符串

如何根据另一个字段更新 mongodb 中的数组 dict 元素

MongoDB 从其他集合中获取数组中最常用的类别以及计数

如何从不同的方法打印多个变量?

MongoDB 对数组中的元素进行分组