Home > Mobile >  how to get objects from array by value inside desired object by mongoose
how to get objects from array by value inside desired object by mongoose

Time:09-12

I have following bson data in mongoDB

{
 name : "company 1",
 createPurchaseOrder :[
  {
     partyName : "p1",
     poNumber : "789",
  },
  {
     partyName : "p2",
     poNumber : "700",
  },
  {
     partyName : "p3",
     poNumber : "889",
  },
 {
     partyName : "p1",
     poNumber : "800",
  },
 {
     partyName : "p1",
     poNumber : "200",
  },
 ]
}

I want objects from partyName for example if partyName is p1 then I want this

[
    {
        partyName: 'p1',
        poNumber: '789',
    },
    {
        partyName: 'p1',
        poNumber: '800',
    },
    {
        partyName: 'p1',
        poNumber: '200',
    },
];

I tried this

const user1 = await User.findOne({name : "company 1"},{createPurchaseOrder:{$elemMatch:{partyName:"p1"}}})

its gives me only first matched object, then I tried this

const user1 = await User.find({name : "company 1"},{createPurchaseOrder:{$elemMatch:{"partyName.$":"p1"}}})

it returned an empty array. please help me with this I want solution which gives me all objects which have matched value

CodePudding user response:

You need to use the aggregation pipeline for this, the find operator is very limited with what structure transformation it can do and for example this use case can't be achieved using it.

Just use $filter instead:

db.collection.aggregate([
  {
    $match: {
      name: "company 1"
    }
  },
  {
    $addFields: {
      createPurchaseOrder: {
        $filter: {
          input: {
            $ifNull: [
              "$createPurchaseOrder",
              []
            ]
          },
          cond: {
            $eq: [
              "$$this.partyName",
              "p1"
            ]
          }
        }
      }
    }
  },
  {
    $unwind: "$createPurchaseOrder"
  },
  {
    $replaceRoot: {
      newRoot: "$createPurchaseOrder"
    }
  }
])

Mongo Playground

  • Related