Friday 5 May 2017

$match with conditions $and in an inner array of an object mongodb

I have a document in Mongo DB with the following structure:

{
    "username" : "John Doe",
    "userdocument" : "1026254745",
    "user_id" : "6QH70tZrPbTDvqmOtUCcT9",
    "createAt" : ISODate("2017-03-22T22:01:15.808Z"),
    "network_clients" : [ 
        {
            "client_id" : "6XvzpJ2IwnVT66pEkKU7E3",
            "_id" : ObjectId("58d2f47dc9a288179cecb996"),
            "usertype" : "client"
        }, 
        {
            "client_id" : "07nPfV5TEH1qTLDBK2xIMe",
            "_id" : ObjectId("58d321aa26417b20f34bc7e7"),
            "usertype" : "client"
        }, 
        {
            "client_id" : "3b45WntXG6KMX12qSEyMGc",
            "_id" : ObjectId("590baf16ea97a217e4834370"),
            "usertype" : "supplier"
        }
    ],
    "useravatar" : "https://pos-lisa.s3.amazonaws.com/useravatar-1493859018209.jpg",
    "comments" : "",
}

I like to make a filter with the "client_id" and the "usertype" fields. I am trying the following in mongoDB with mongoose:

User.aggregate({ $match:
    { $and: 
        [
            { 'network_clients.client_id': clientId }, 
            { 'network_clients.usertype': userType }
        ] 
    }
}).sort({ username: 'ascending' })

In my app, a user can be a supplier of one of my clients, and the same user can be a client of other of my clients, but with this implementation, mongo always send me the user no matter if he is client or supplier, so my client see the user in the "client list" and in the "supplier list"

How can I make the filter in the inner array of this document? In advance thanks



via maoooricio

No comments:

Post a Comment