【问题标题】:How can I get only the array element as output instead of whole object in MongoDB?如何在 MongoDB 中仅获取数组元素而不是整个对象作为输出?
【发布时间】:2021-12-11 04:28:49
【问题描述】:

以下是我的代码,用于显示作为餐厅集合对象一部分的评论数组数据:

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

我的对象看起来像:

{
  _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: []
}

我的输出如下:

{
    "_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"
        }
    ]
}

我想要的输出:

{
    "_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"
}

如何在不获取餐厅 ID 或整个对象的情况下仅获取评论的输出?

【问题讨论】:

    标签: node.js arrays mongodb objectid


    【解决方案1】:

    因此查询运算符findfindOne 不允许“高级”数据重组。

    所以你有两种选择:

    1. 更常见的方法是在代码中执行此操作,通常人们要么使用某些东西 mongoose post trigger,要么使用某种“共享”函数来处理所有这些转换,这就是避免代码重复的方法。

    2. 使用聚合框架,如下所示:

    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2018-04-19
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多