wcyat
wcyat

Reputation: 77

MongoDB get a partial document

I have a document stored in MongoDB:

{
   "id": 1,
   "op": "someone",
   "title": "some title",
   "category": 1,
   "conversation": {
      "1": {
         "user": 2,
         "comment": "some comment"
      },
      "2": {
         "user": 9,
         "comment": "comment 2"
      },
      ......
      "26": {
         "user": 5,
         "comment": "comment 26"
      }
   }
}

I want to get this on request: (e.g. POST {"id":1, "page":2})

{
  "id": 1,
  "op": "someone",
  "title": "some title",
  "category": 1,
  "conversation": {
     "11": {
        "user": 10,
        "comment": "comment 11"
     },
     ......
     "20": {
        "user": 25,
        "comment": "comment 25"
     }
   }
}

i.e. 10 comments starting on 11, that is

page 1: return comments 1 - 10,

page 2: return comments 11 - 20,

......

page 10: return comments 91 - 100

I am using NodeJS. Since processing this in node can use up a lot of memory. I would like to do this in Mongo.

Upvotes: 0

Views: 728

Answers (2)

bemo
bemo

Reputation: 489

You can use the Mongo aggregation pipeline to do some powerful reshaping of documents.

It looks like the $redact stage would do what you want - there's a very similar example on the MongoDB site where they want to retrieve specific elements from arrays within documents.

Upvotes: 3

Alexandre LEROY
Alexandre LEROY

Reputation: 2310

In order to make that process on MongoDB side, you can use skip() and limit() function

const document_by_page = 10;
const page = 1;

db.collection.find().skip(page * document_by_page).limit(document_by_page);

With the new information from your comments, you should use mongo db pipeline to process information on MongoDB side. Take a look at https://docs.mongodb.com/manual/reference/operator/aggregation/filter/#mongodb-expression-exp.-filter.

Have a great day finding your solution

Upvotes: 2

Related Questions