简体   繁体   中英

How do I display only part of the array after findOne in MongoDB?

Restaurants is a collection and has objects like below:

{
    _id: new ObjectId("61723c7378b6d3a5a02d908e"),
    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: new ObjectId("61736a0f65b9931b9e428789"),
        title: 'asd',
        reviewer: 'khoh',
        rating: 3,
        dateOfReview: '5/12/2002',
        review: 'hey'
      },
        _id: new ObjectId("61736a0f65b9931b9e428790"),
        title: 'dom',
        reviewer: 'firuu',
        rating: 4,
        dateOfReview: '25/1/2002',
        review: ' bruh'
      }
    ]
  }

I am using the below code to find this object based on the review id provided

async get(reviewId) {

    const restaurantsCollection = await restaurants();
    reviewId = ObjectId(reviewId)
    const r = await restaurantsCollection.findOne({reviews: {$elemMatch: {_id: reviewId}}})
    return r

This returns the whole object from the restaurant collection, what do I do if I want only the review displayed whose id is provided in get(reviewID)

Output:

{
  _id: new ObjectId("61736a0f65b9931b9e428790"),
   title: 'dom',
   reviewer: 'firuu',
   rating: 4,
   dateOfReview: '25/1/2002',
   review: ' bruh'
}

With a projection, specify the fields to return

The following returns only the review whose id is provided in get(reviewID)

async get(reviewId) {
  const restaurantsCollection = await restaurants();
  reviewId = ObjectId(reviewId)

  const r = await restaurantsCollection.findOne(
    { reviews: { $elemMatch: { _id: reviewId } } },
    { "reviews.$": 1 }
  )

  return r
}

Test Here

You can also use find instead of fineOne

Query

  • replace the ObjectId("61736a0f65b9931b9e428789") with reviewId
  • this will return the reviews that match the _id in an array
  • if you want to get the first only, in case there is always max 1 you can replace the last project with {"$project": {"_id": 0, "review": {"$arrayElemAt": ["$reviews", 0]}}}

*not sure if this is what you need

Test code here

aggregate(
[{"$match": {"reviews._id": ObjectId("61736a0f65b9931b9e428789")}}
 {"$set": 
   {"reviews": 
     {"$filter": 
       {"input": "$reviews",
        "cond": 
        {"$eq": ["$$this._id", ObjectId("61736a0f65b9931b9e428789")]}}}}},
  {"$project": {"_id": 0, "reviews": 1}}])

这可能不是您问题的正确答案,但您可以尝试这样的操作。

const r = await restaurantsCollection.findOne({reviews: {$elemMatch: {_id: reviewId}}})?.reviews.find(review => review._id.equals(reviewId))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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