Saif Ali Khan
Saif Ali Khan

Reputation: 848

MongoDB - Query on the last object of an array?

Is there any way in MongoDB in which I can specifically query on last object's key value in an array in a single db query.

For eg: This is my doc in a collection.

{
  "com" : [ 
    { "ts" : 1510830164203, "com" : "com1" }, 
    { "ts" : 1511242569673, "com" : "connected" },
    { "ts" : 1511244832741, "com" : "vb" } 
  ],
  "status" : [ 
    { "ts" : 1510857000000, "stat" : 3 } 
  ] 
}

So as you can see there are multiple objects in com. How can I query on last object's ts(timestamp) or I want to check is last com inserted in between today's date or not.

I have already gone through this link. But didn't find the appropriate solution.

Any help can be appreciated.

Upvotes: 2

Views: 7620

Answers (4)

PJ-ZO
PJ-ZO

Reputation: 1

You can use the below project query if you only need to find the last element.

db.collection.find({},{status: 1, com:{$slice: -1}})

More discussion on the similar topic here

Upvotes: 0

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $match: {
             "_id" : ObjectId("5a197a3bde472b16ed9fc28d")
            }
        },

        // Stage 2
        {
            $unwind: {
                path : "$com"
            }
        },

        // Stage 3
        {
            $sort: {
             'com.ts':-1
            }
        },

        // Stage 4
        {
            $limit: 1
        }

    ]



);

Upvotes: 0

Elie Asmar
Elie Asmar

Reputation: 3165

var d1 = new Date( parseInt( "Today at 12:00 AM", 16 ) * 1000 )
var d2 = new Date( parseInt( "Tomorrow at 12:00 AM", 16 ) * 1000 )

db.table.find(
   { com: { $elemMatch: {ts:{ $gte: d1, $lt: d2 } } } })
)

Upvotes: 0

Shaishab Roy
Shaishab Roy

Reputation: 16805

You can use $arrayElemAt to get the last element and then match applied in aggregation. To get the last element using $arrayElemAt use second value -1 that indicate last element of an array. $arrayElemAt: ["arrayName", -1]. code will be like

db.collectionName.aggregate([
  {
    $project: {
      status: 1,
      com: {$arrayElemAt: ["$com", -1]}
    }
  },
  {
    $match: {"com.ts": 15115465465}
  }
])

N.B: if you want to compare like less than or greater than then use like : $lt, $lte, $gt, or $gte any one that you need

$match: {"com.ts": {$lt: 15115465465}}

Upvotes: 2

Related Questions