Pipeline in lookup aggregation not working in mongodb - mongodb

I am new to mongodb so I hope this does not come-off as a very elementary question. I've done some research and tried to apply what I've found but something just seems to escape me.
I have two collections of the following format:
-----------------------------------------------------------------------
Shop
-----------------------------------------------------------------------
{
"shopId": "1002",
"shopPosId": "10002",
"description": "some description"
}
-----------------------------------------------------------------------
Compte
-----------------------------------------------------------------------
{
"shopId": "9000",
"shopPosId": "0000",
"clientUid": "474192"
}
I want to join those and before doing so, I want to filter out the Shops which do not have the shopPosId field.
Here's my code:
Compte.aggregate([
{
$match:
{
$and:[{"clientUid":clientUid}]
}
},
{
$lookup:
{
from: "Shop",
localField: "shopId",
foreignField: "shopId",
let: {"Shop.shopPosId": "$shopPosId"},
pipeline: [{$match: {"shopPosId": {"$exists": false}}}],
as: "shopDescr"
}
}]
);
the returned result is an undefined, which means the query doesn't make much sense (because in fact I should at least get a void array).
Is this because the two collections have the shopPosId field? (if so, isn't this line let: {"Shop.shopPosId": "$shopPosId"} supposed to take care of it ?)

As Alex commented you are mixing both the $lookup syntax here... So the correct will be
Compte.aggregate([
{ "$match": { "$and": [{ "clientUid": clientUid }] }},
{ "$lookup": {
"from": "Shop",
"let": { "shopId": "$shopId" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$shopId", "$$shopId" ] },
"shopPosId": { "$exists": false }
}}
],
"as": "shopDescr"
}}
])

Related

MongoDB Aggregation use value from Match Object in pipelin

i'm using the following aggregation:
const aggregate = [
{
$match: {
mainCatId: new ObjectId(catId),
},
},
{
"$lookup": {
"from": "products",
"pipeline": [
{ "$match": { "subCategory": '$_id' } },
],
"as": "products"
}
},
{ "$unwind": "$products" }
];
The problem is that i have to match the id of each doc in the pipeline section but this is not working. So the question is how can i match the id i"m getting from the match above
Is the syntax below, which uses the traditional syntax for single join conditions, what you are looking for?
const aggregate = [
{
$match: {
mainCatId: new ObjectId(catId),
},
},
{
"$lookup": {
"from": "products",
localField: "subCategory",
foreignField: "_id",
"as": "products"
}
},
{
"$unwind": "$products"
}
]
If not, please provide sample documents and further details about the ways in which your current approach (and this proposed solution) are not working.

Filter query for fetching product based on categories in MERN application?

This is my Product Schema
const product = mongoose.Schema({
name: {
type: String,
},
category:{
type: ObjectId,
ref: Category
}
}
I want to return the product based on filters coming from the front end.
For example: Lets consider there are 2 categories Summer and Winter. When the user wants to filter product by Summer Category an api call would me made to http://localhost:8000/api/products?category=summer
Now my question is, how do I filter because from the frontend I am getting category name and there is ObjectId in Product Schema.
My attempt:
Project.find({category:categoryName})
If I've understood correctly you can try one of these queries:
First one is using pipeline into $lookup to match by category and name in one stage like this:
yourModel.aggregate([
{
"$lookup": {
"from": "category",
"let": {
"category": "$category",
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$id",
"$$category"
]
},
{
"$eq": [
"$name",
"Summer"
]
}
]
}
}
}
],
"as": "categories"
}
},
{
"$match": {
"categories": {
"$ne": []
}
}
}
])
Example here
Other way is using normal $lookup and then $filter the array returned by join.
yourModel.aggregate([
{
"$lookup": {
"from": "category",
"localField": "category",
"foreignField": "id",
"as": "categories"
}
},
{
"$match": {
"categories": {
"$ne": []
}
}
},
{
"$set": {
"categories": {
"$filter": {
"input": "$categories",
"as": "c",
"cond": {
"$eq": [
"$$c.name",
"Summer"
]
}
}
}
}
}
])
Example here
Note how both queries uses $match: { categories: { $ne : []}}, this is because if the lookup doesn't find any result it returns an empty array. By the way, this stage is optional.
Also you can add $unwind or $arrayElemAt index 0 or whatever to get only one value from the array.
Also, to do it in mongoose you only need to replace "Summer" with your variable.

how to sort aggregate - Mongodb

db.getCollection('shows').aggregate([
{ $match: { _id: ObjectId("5d622cecbbe890f60ccd1ca4") } },
{ $lookup: { from: "episode", // collection name in db
localField: "_id",
foreignField: "show_id",
as: "episode"
}
},
{ $sort: { 'episode._id': 1 } }
])
So the below works fine however it seems that the sort is not sorting the collection episode in the correct order. It is still putting it oldest to newest when I want to have it newest to oldest.
I am wondering how this is done?
You can use below aggregation
db.getCollection("shows").aggregate([
{ "$match": { "_id": ObjectId("5d622cecbbe890f60ccd1ca4") } },
{ "$lookup": {
"from": "episode",
"let": { "episodeId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$show_id", "$$episodeId"] }}},
{ "$sort": { "_id": 1 }}
],
"as": "episode"
}}
])

MongoDB: Lookup - Collections with Same Fields

I've two collections Users and Notes. Both collections contain an id property and the Notes collection has an userid that is the id of some user on the Users collection.
Now, I'm trying to aggregate (join) some user information into Notes:
db.getCollection("Notes").aggregate(
{
"$lookup": {
"from": "Users",
"let": {
"idForeignField": "$id"
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [{
"$eq": ["$userid", "$$idForeignField"]
}]
}
}
}
],
"as": "Users#joined"
}
}
);
What I get in a empty Users#joined array. Why? Shouldn't my query work? Is the problem caused by the fact that both collections have an id property? If yes how can I tell let and match what is the right collection?
Update: alternatively a simpler query works just fine:
db.getCollection("Notes").aggregate(
{
$lookup:
{
from: "Users",
localField: "userid",
foreignField: "id",
as: "Users#joined"
}
}
);
However I would like to do it with let and a pipeline in order to add more match conditions.
Thank you.
Your let variable must be userid
db.getCollection("Notes").aggregate([
{ "$lookup": {
"from": "Users",
"let": { "ifForeignField": "$userid" },
"pipeline": [
{ "$match": { "$expr": { "$and": [{ "$eq": ["$id", "$$ifForeignField"] }] }}}
],
"as": "Users#joined"
}}
])

How can I use a field from aggregate in a regex $match in mongodb?

A very simplified version of my use case is to find all posts beginning with the authors name, something like this:
> db.users.find();
{ "_id" : ObjectId("5c4185be19da7e815cb18f59"), "name" : "User1" }
{ "_id" : ObjectId("5c4185be19da7e815cb18f5a"), "name" : "User2" }
db.posts.insert([
{author : ObjectId("5c4185be19da7e815cb18f59"), text: "User1 is my name"},
{author : ObjectId("5c4185be19da7e815cb18f5a"), text: "My name is User2, but this post doesn't start with it"}
]);
So I want to identify all posts that start with the authors name. I'm trying with an aggregate like this, but I don't know how to extract the user's name from the aggregate pipeline to use in a regex match:
db.users.aggregate([
{
$lookup: {
from: "posts",
localField: "_id",
foreignField: "author",
as: "post"
}
},
{
$match: { "post.text": { $regex: "^" + name}}
}
]).pretty();
The thing "name" here is not something defined, I need to extract the name from the users collection entry from the previous step of the pipeline. For some reason I don't understand how to do that.
This is probably super simple and I'm definitely feeling thick as a brick hereā€¦ Any help highly appreciated!
You can use below aggregation using $indexOfCP
db.users.aggregate([
{ "$lookup": {
"from": "posts",
"let": { "authorId": "$_id", "name": "$name" },
"pipeline": [
{ "$match": {
"$expr": {
"$and": [
{ "$ne": [{ "$indexOfCP": ["$text", "$$name"] }, -1] },
{ "$eq": ["$author", "$$authorId"] }
]
}
}}
],
"as": "post"
}}
])