I'm beginner to mongodb and I'm trying to write a query using mongoose in node.js application:
const objectIdValue = secondId.valueOf();
const existedRelation = await this.model.aggregate([
{ $match: { _id: firstId } },
{ $project: {
relations: {
$filter: {
input: '$links',
as: 'link',
cond: {
$and: [
{ $eq: ['$$link.target.entityId', `${objectIdValue}`] },
{ $eq: ['$$link.linkTypeId', linkTypeId] },
],
},
},
},
},
},
]);
console.log('existedRelation: ', existedRelation);
When I execute it I got this result:
existedRelation: []
I tried to execute it using mongoShell:
db.tasks.aggregate([
{ $match:{ _id: ObjectId("5bbf5800be37394f38a9727e") }},
{
$project: {
relations:{
$filter:{
input: '$links',
as: "link",
cond: {
$and: [
{$eq:["$$link.target.entityId", '5bbf52eabe37394f38a97276']},
{$eq: ["$$link.linkTypeId", ObjectId("5bbf4bfcb075e03bd4a1b779")]}
]
}
}
}
}
}
And I got the results that I want. What is the mistake that I made ?
Aggregation wins where the volume of data returned is much less than the original data or where you don't have the skill to build fast client side aggregations. I hope it answers your query.
General idea is to use findOne https://docs.mongodb.com/manual/reference/method/db.collection.findOne/ to retrieve one random id from the duplicate records in the collection. Delete all the records in the collection other than the random-id that we retrieved from findOne option.
Mongoose doesn't cast String
to ObjectId
in aggregate function. So you have to cast it manually using mongoose.
var mongoose = require('mongoose')
const existedRelation = await this.model.aggregate([
{ "$match": { "_id": mongoose.Types.ObjectId(firstId) } },
{ "$project": {
"relations": {
"$filter": {
"input": "$links",
"as": "link",
"cond": {
"$and": [
{ "$eq": ["$$link.target.entityId", `${objectIdValue}`] },
{ "$eq": ["$$link.linkTypeId", linkTypeId] }
]
}
}
}
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With