Reputation: 3476
I have a list of items similar to this:
{
user: "ObjectId(...)"
type: "foo",
subType: "foo_bar",
state: "active",
accounts: [ObjectId(...)]
}
I need to create a MongoDB query (I'm not very familiar with it) that exclude all subtype: "foo_bar"
if the state: "active"
.
Looking at the docs I'm trying to use $not
but I do receive error: unknown top level operator: $not
Trying many different queries that would be unnecessary to report here because are all containing errors...
These is the base query that is working fine and I need to attach the new condition:
db.items.find({ $or: [{ user: myUser._id }, { accounts: { $in: myAccountsVariable } }], state: { $ne: "closed" } })
Can someone help me achieve this? Thanks
Upvotes: 1
Views: 1109
Reputation: 851
You can try something like db.items.find({"$or": [{state: "active", subType: {"$ne": "foo_bar"}}, {state: {"$ne": "active"}}]})
This should return every item that's either active (but not foo_bar) or not active (any subtype)
EDIT:
Adding it to your base query should be something like
db.items.find(
{ "$and": [
{ $or: [{ user: myUser._id }, { accounts: { $in: myAccountsVariable } }], state: { $ne: "closed" } },
{"$or": [{state: "active", subType: {"$ne": "foo_bar"}}, {state: {"$ne": "active"}}]}
]
}
)
Upvotes: 0
Reputation: 49975
You can revert your criteria and use $or
with $ne
:
db.collection.find({ $or: [ { state: { $ne: "active" } }, { subType: { $ne: "foo_bar" } } ] })
Just add this to your existing query using $and
operator
db.collection.find({ $and: [
{ $or: [ { state: { $ne: "active" } }, { subType: { $ne: "foo_bar" } } ] },
{ $or: [{ user: myUser._id }, { accounts: { $in: myAccountsVariable } }], state: { $ne: "closed" } }
] })
Upvotes: 1