0

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

maoooricio
  • 2,249
  • 3
  • 15
  • 19
  • Possible duplicate of [How to filter array in subdocument with MongoDB](http://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb) – s7vr May 05 '17 at 14:58

1 Answers1

0

I am not sure I am following you in exactly what you want to do. But maybe this is something close to it:

User.aggregate({$project:{'username':1,'network_clients':1}},
{$unwind:'$network_clients'},
{$match:{'network_clients.client_id':clientId,'network_clients.usertype':userType}},
{$sort:{username:1}})
tomtom
  • 642
  • 7
  • 12
  • You are absolutely right! And here in SO, the rule is: not send a 'thank you', but I send to you one million of them! :) – maoooricio May 05 '17 at 15:41