Home > Back-end >  get additional data on same collection in Mongodb C#
get additional data on same collection in Mongodb C#

Time:04-08

I have a collection called "User". I'm passing userid to get the record. In addition to that i also need additional 10 last updatedAt(DateTime) record excluding the userid record but added together. So, total returned result will be 11 in this case. Is that possible using same query? I tried using Or and lookup but can't make it work as expected. Any help is appreciated.

CodePudding user response:

Edit: You can use $facet, like this:

db.collection.aggregate([
  {$sort: {date: -1}},
  {$facet: {
      byTate: [{$limit: 10}],
      byUser: [{$match: {userId: 455845}}]
    }
  },
  {$project: {
    byDate: {
        $filter: {
            input: "$byDate",
            as: "item",
            cond: {$ne: ["$$item",{"$arrayElemAt": ["$byUser", 0]}]}
        }
    },
    byUser: 1,
    }
  },
  {
    $project: {
      byDate: {$slice: ["$byDate", 10]},
      byUser: 1
    }
  }
])

You can see it works on the playground .

Switch between userId: 455845 / 455845 to see both cases.

  • Related