I'm trying to match documents based on the fact that their _id is not present in ObjectId's Array of their own.
Mongodb version: 3.2
Here's my query :
db.subscriptions.aggregate(
[
{ $match : { "device": { $exists: true } } },
{
$lookup : {
from: "devices",
localField: "device",
foreignField: "_id",
as: "device"
}
},
{ $match : { "device.0" : { $exists: true } } },
{ $unwind: "$device" },
{ $project : {"_id": 1, "subs": "$device.subscriptions" } },
{ $match: { "_id": { $in: this.subs } } }
]
)
I have two collection subscriptions and devices. The document subscription have a property device which is an ObjectId refering to a device. The device document have an array of objectId refering to the subscriptions. It's a one-to-many relationship.
Step 1: Matching subscription who actualy have the device property (it's not a clean clean db)
Step 2: I'm performing a lookup to get my device document inside the subscription
Step 3: Once again matching the fact that the lookup did give result
Step 4: Unwind the device cause the lookup thing give me an array (i dont quite understand why tho')
Step 5: Projecting the subscriptions array and the subscription id to work with simpler document:
{
"_id" : ObjectId("587e265cb9b235243c7f9960"),
"subs" : [
ObjectId("5899a894b1e11521a44a96f7"),
ObjectId("5a8c494db0bed60b389cb1da")
]
}
Step 6: This is where the error appear, mongo's teling me this.subs is not an array so i cant use $nin => "errmsg" : "$in needs an array"
I've tried multiple format: "this.subs", "$subs", none of that works.
Can somebody helps me ?
Théo