0

I have data saved in the following:

{ 
    "_id" : ObjectId("57723b5e009793e8f3cfd1d7"), 
    "room" : "1003", 
    "inout" : {
        "1" : [
            "i1654", 
            "o1656", 
            "i1706", 
            "o1707", 
        ], 
        "2" : [
            "i1655", 
            "o1656", 
            "i1715", 
            "o1715"
        ], 
        "3" : [
            "i1801"
        ]
    }
}

how to count and paginate the subdocument "inout" which is an object?

thanks!!!

1 Answers1

1

Actually, there is a small modification required in your JSON. The "inout" should be an array to use the below solution.

"$unwind" can be used here.

Modified JSON to define "inout" as array rather than Object:-

db.rooms_second.insertOne({ 
    "_id" : ObjectId("57723b5e009793e8f3cfd1d7"), 
    "room" : "1003", 
    "inout" : [
        {"1" : [
            "i1654", 
            "o1656", 
            "i1706", 
            "o1707", 
        ]}, 
        {"2" : [
            "i1655", 
            "o1656", 
            "i1715", 
            "o1715"
        ]}, 
        {"3" : [
            "i1801"
        ]}
    ]
});

Mongodb Query:-

In the resultset, the below query will give you one record for each element in the "inout" array.

db.rooms_second.aggregate([ { $unwind: "$inout" } ])

The pagination can be done based on the driver and API that you are using (i.e. MongoDB Java Driver etc.).

notionquest
  • 37,595
  • 6
  • 111
  • 105
  • If change inout to an array, how to push more values to keys 1 or 2 or 3? And how to push a new key 4 under inout? @notionquest Thanks. – zackwang Jul 01 '16 at 01:58