简体   繁体   中英

MongoDB match id not in multiple arrays

Im trying to aggregate objects in MongoDB using Moongoose (NestJS Wrapper) and running into issues filtering data. I have a field profileID, which is used by different collections to link objects. Im using the match operator to filter based on multiple properties and cant seem to figure out how to do the following:

Filter the profileID by checking if its not in multiple different arrays here is what I've attempted so far (adapted an answer from another post)

return this.userProfile.aggregate(
[{ $match: {
           ...
           profileId: {
               $or: [
                 {$nin: userData.blocked},
                 {$nin: userData.matches},
                 {$nin: userData.rejects},
                 {$nin: userData.unmatched}]
         }
       ...

}

Im getting the following error now:

[Nest] 20356   - 12/24/2019, 22:42:34   [ExceptionsHandler] unknown operator: $or +77161ms
MongoError: unknown operator: $or

I also get errors if I try to have individual not in with multiple profileID fields

TS1117: An object literal cannot have multiple properties with the same name in strict mode.
TS2300: Duplicate identifier 'profileID'.

$or is a top-level command, so you need to do something more like...

return this.userProfile.aggregate(
[{ $match: {
           ...
               $or: [
                 { profileId: {$nin: userData.blocked}},
                 { profileId: {$nin: userData.matches}},
                 { profileId: {$nin: userData.rejects}},
                 { profileId: {$nin: userData.unmatched}}
             ]
         }
       ...

}

which I did as an example if you really want to have separate $nin conditions. Instead, it would be better to have only on $nin with all the values combined in a single array (and then you won't need a $or) like so

return this.userProfile.aggregate(
[{ $match: {
       ...
        profileId: {
            $nin: [...userData.blocked, ...userData.matches, ...userData.rejects, ...userData.unmatched]
         }
       ...

}

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.

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