I need to get a variety of items in my MongoDB collection based on an $or
statement.
Following these official docs the query I have constructed looks acceptable, yet the first $gt
statement is not being fulfilled. It is returning items that have a quantity
equal to zero.
let query = {};
query.$or = [ { 'quantity': { $gt: 0 } }, { type: { $in: [ITEM_TYPE_A, ITEM_TYPE_B] } }];
db.Items.find(query).then( res => res)
Could it be the dot
syntax appending a new key/value pair to the query object? Unfortunetly this query is just one of many that get appended to the query
object based on if
statements. Ex. if (something) query.field = value
I can't figure out why, but using the Object.assign
method fixed my query.
Instead of:
query.$or = [ { 'quantity': { $gt: 0 } }, { type: { $in: [ITEM_TYPE_A, ITEM_TYPE_B] } }]
I did:
query = Object.assign({}, query, { $or: { 'quantity': { $gt: 0 } }, { type: { $in: [ITEM_TYPE_A, ITEM_TYPE_B]}
you can use one of following
let query = {};
query = {...query,$or:[ { 'quantity': { $gt: 0 } }, { type: { $in: [ITEM_TYPE_A, ITEM_TYPE_B] } }]};
or
query = Object.assign({}, query, { $or: [ { 'quantity': { $gt: 0 } }, { type: { $in: [ITEM_TYPE_A, ITEM_TYPE_B] } }]});
or
query["$or"] = [ { 'quantity': { $gt: 0 } }, { type: { $in: [ITEM_TYPE_A, ITEM_TYPE_B] } }];
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.