从mongodb获取特定字段并作为对象数组返回

我有以下文件:

"content": [
    {
        "_id": "5dbef12ae3976a2775851bfb","name": "Item AAA","itemImages": [
            {                 
                "_id": "5dbef12ae3976a2775851bfd","imagePath": "https://via.placeholder.com/300","imageTitle": "Test 300"
            },{
                "_id": "5dbef12ae3976a2775851bfc","imagePath": "https://via.placeholder.com/250","imageTitle": "Test 250"                 
            }
        ]
    }

,我想知道是否有一种方法可以只返回数组中的数据,但带有“名称”和文档“ main _id”,以便结果集为

        "itemImages": [
            {                 
                "_id": "5dbef12ae3976a2775851bfb",{
                "_id": "5dbef12ae3976a2775851bfb","imageTitle": "Test 250"                 
            }
        ]

我尝试使用mongodb find和聚合函数,但都没有帮助检索上述结果。谢谢您的帮助

chenocean 回答:从mongodb获取特定字段并作为对象数组返回

您应该能够通过聚合获得想要的东西。

您需要:

  • 展开数组,以便每个元素都有一个单独的文档
  • 使用addFields将_id和名称添加到元素
  • 分组以重新组装数组
  • 仅获取所需字段的项目

这可能看起来像:

declare -p var
本文链接:https://www.f2er.com/3155806.html

大家都在问