简体   繁体   English

如何在 MongoDB 中只获取数组元素而不是整个对象作为输出?

[英]How can I get only the array element as output instead of whole object in MongoDB?

Below is my code to display review array data which is part of the restaurant collection object:下面是我的代码,用于显示作为餐厅集合对象一部分的评论数组数据:

async get(reviewId) {
    const restaurantsCollection = await restaurants();
    reviewId = ObjectId(reviewId)
  
    const r = await restaurantsCollection.findOne(
      { reviews: { $elemMatch: { _id : reviewId } } },
      {"projection" : { "reviews.$": true }}
    )
  
    return r
  }

My object looks like:我的对象看起来像:

{
  _id: '6176e58679a981181d94dfaf',
  name: 'The Blue Hotel',
  location: 'Noon city, New York',
  phoneNumber: '122-536-7890',
  website: 'http://www.bluehotel.com',
  priceRange: '$$$',
  cuisines: [ 'Mexican', 'Italian' ],
  overallRating: 0,
  serviceOptions: { dineIn: true, takeOut: true, delivery: true },
  reviews: []
}

My output looks like:我的输出看起来像:

{
    "_id": "6174cfb953edbe9dc5054f99", // restaurant Id
    "reviews": [
        {
            "_id": "6176df77d4639898b0c155f0", // review Id
            "title": "This place was great!",
            "reviewer": "scaredycat",
            "rating": 5,
            "dateOfReview": "10/13/2021",
            "review": "This place was great! the staff is top notch and the food was delicious!  They really know how to treat their customers"
        }
    ]
}

What I want as output:我想要的输出:

{
    "_id": "6176df77d4639898b0c155f0",
    "title": "This place was great!",
    "reviewer": "scaredycat",
    "rating": 5,
    "dateOfReview": "10/13/2021",
    "review": "This place was great! the staff is top notch and the food was delicious!  They really know how to treat their customers"
}

How can I get the output as only the review without getting the restaurant ID or the whole object?如何在不获取餐厅 ID 或整个对象的情况下仅将输出作为评论?

So the query operators, find and findOne do not allow "advanced" restructure of data.因此查询运算符findfindOne不允许对数据进行“高级”重组。

So you have 2 alternatives:所以你有两个选择:

  1. The more common approach will be to do this in code, usually people either use some thing mongoose post trigger or have some kind of "shared" function that handles all of these transformations, this is how you avoid code duplication.更常见的方法是在代码中执行此操作,通常人们要么使用某种东西mongoose post trigger要么使用某种“共享”函数来处理所有这些转换,这就是避免代码重复的方法。

  2. Use the aggregation framework, like so:使用聚合框架,如下所示:

const r = await restaurantsCollection.aggregate([
    {
        $match: { reviews: { $elemMatch: { _id : reviewId } } },
    },
    {
        $replaceRoot: {
            newRoot: {
                $arrayElemAt: [
                    {
                        $filter: {
                            input: "$reviews",
                            as: "review",
                            cond: {$eq: ["$$review._id", reviewId]}
                        }
                    },
                    0
                ]
            }
        }
    }
])
return r[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM