FranciscoJxL
FranciscoJxL

Reputation: 23

How can you find all documents that match the last element of an array field with a given query value in Mongoose?

I have a Collection with a structure similar to:

type Products {
       productid: String
       owners: [String]
}

In my query, I'm inputting a value user. I need to retrieve all documents that match the last element in owners, hopefully using find. I've tried Products.find({ "$owners.-1": user }) with no luck so far

Is there any way to access the last element of this array?

Upvotes: 2

Views: 49

Answers (2)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

If you mean to get only the documents where passed in user value is the last element in owners array from Products collection, then try this :

var user = 'myname';    
Products.find( { $expr: {$eq : [{ $arrayElemAt: [ '$owners', -1 ] }, user]} })

Collection Data :

/* 1 */
{
    "_id" : ObjectId("5e1f82b0d02e05b694b48b9d"),
    "productid" : "1",
    "owners" : [ 
        "others", 
        "myname"
    ]
}

/* 2 */
{
    "_id" : ObjectId("5e1f84d3d02e05b694b4cbe0"),
    "productid" : "2",
    "owners" : [ 
        "others", 
        "myname", 
        "anothername"
    ]
}

/* 3 */
{
    "_id" : ObjectId("5e1f84e2d02e05b694b4cee2"),
    "productid" : "3",
    "owners" : [ 
        "myname", 
        "anothername"
    ]
}

/* 4 */
{
    "_id" : ObjectId("5e1f84ebd02e05b694b4d0d0"),
    "productid" : "4",
    "owners" : [ 
        "myname"
    ]
}

Result :

 /** Only "productid" : "1" & "productid" : "4" are returned */
/* 1 */
{
    "_id" : ObjectId("5e1f82b0d02e05b694b48b9d"),
    "productid" : "1",
    "owners" : [ 
        "others", 
        "myname"
    ]
}

/* 2 */
{
    "_id" : ObjectId("5e1f84ebd02e05b694b4d0d0"),
    "productid" : "4",
    "owners" : [ 
        "myname"
    ]
}

Upvotes: 2

Kaiser Wilhelm
Kaiser Wilhelm

Reputation: 618

The following will give you the last element in the owners list.

db.Products.find( {}, { owners: { $slice: -1 } } );

Upvotes: 1

Related Questions