简体   繁体   English

如何在 Mongoose/MongoDB 中执行 $or 查询?

[英]How to perform an $or query in Mongoose/MongoDB?

I need to get a variety of items in my MongoDB collection based on an $or statement.我需要根据$or语句在我的 MongoDB 集合中获取各种项目。

Following these official docs the query I have constructed looks acceptable, yet the first $gt statement is not being fulfilled.按照这些官方文档,我构建的查询看起来可以接受,但第一个$gt语句没有得到满足。 It is returning items that have a quantity equal to zero.它正在返回quantity为零的项目。

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?可能是将新的键/值对附加到查询对象的dot语法吗? Unfortunetly this query is just one of many that get appended to the query object based on if statements.不幸的是,这个查询只是基于if语句附加到query对象的众多查询之一。 Ex.前任。 if (something) query.field = value

I can't figure out why, but using the Object.assign method fixed my query.我不知道为什么,但使用Object.assign方法修复了我的查询。

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] } }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM