Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find using _id not working with aggregation [duplicate]

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 ?

like image 590
Slim Avatar asked Oct 18 '18 08:10

Slim


People also ask

Is aggregate faster than find?

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.

How do I remove duplicates in MongoDB?

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.


1 Answers

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] }
          ]
        }
      }
    }
  }}
])
like image 138
Ashh Avatar answered Nov 15 '22 06:11

Ashh