I'm brand new to MongoDB and Mongoose. I'm currently building an app that has a client collection that contains an array of accounts that the client has.
I'd like to query the collection based on specifics of the accounts the client has. For example, I need to return the client that is:
Below is a sample document:
{
clientDetails: {
cardNumber: "0123456",
firstName: "Bob",
lastName: "Dole",
clientType: "Standard"
},
accounts: [
{
accountNumber: "123",
accountType: "FML",
balance: 4000.00
},
{
accountNumber: "234",
accountType: "OMG",
balance: 2000
}
]
}
So far, I've only figured out how to build a query that can get a client of clientType "Standard" with accountTypes ["FML","OMG] but I can't figure out how to specify the balance condition for the specific accountTypes.
ClientModel
.find({
"clientDetails.clientType": "Standard",
"accounts.accountType": { $all ["FML", "OMG"]
})
.then(
function(){ //etc..},
function(err){ //etc...}
);
You can use $all
with $elemMatch
.
ClientModel
.find({
"clientDetails.clientType": "Standard",
"accounts":
{
$all: [
{ "$elemMatch" : { accountType: "FML", balance: { $gt: 3000} } },
{ "$elemMatch" : { accountType: "OMG", balance: { $lt: 3000} } }
]
}
})
.then(
function(){ //etc..},
function(err){ //etc...}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.