Search code examples
mongodbmongoosemongoose-schema

how to query mongoose based on OR condition


i have a transaction collection and i require to query this from mongoose

    _id: 5ecba0d446d0354084ad0b89
    amount: 3
    userId: 5ec3285cc7762963c88db765
    type: 4
    userType: 1
    recipientId: 5ec328f2c7762963c88db768
    status: "succeeded"
    createdAt: 2020-05-25T10:41:24.449+00:00
    updatedAt: 2020-05-25T10:41:24.449+00:00
    __v: 0


    _id: 5ecba0d446d0354084ad0b92
    amount: 4
    userId: 5ec3285cc7762963c88db888
    type: 4
    userType: 1
    recipientId: 5ec3285cc7762963c88db765
    status: "succeeded"
    createdAt: 2020-05-25T10:41:24.449+00:00
    updatedAt: 2020-05-25T10:41:24.449+00:00
    __v: 0


    _id: 5ecba0d446d0354084ad0b97
    amount: 8
    userId: 5ec3285cc7762963c88db332
    type: 4
    userType: 1
    recipientId: 5ec328f2c7762963c88db589
    status: "succeeded"
    createdAt: 2020-05-25T10:41:24.449+00:00
    updatedAt: 2020-05-25T10:41:24.449+00:00
    __v: 0

how to query this such that i can get the transactions based on following condition

userId = 5ec3285cc7762963c88db765 or recipientId = 5ec3285cc7762963c88db765
and type = 4
and userType = 1

Solution

  • use $or and $and operators

    model.find({
       $or: [ 
         { userId: 5ec3285cc7762963c88db765 },
         { recipientId: 5ec3285cc7762963c88db765 }
       ],
       $and: [ { type: 4 }, { userType: 1 } ]
    });