简体   繁体   中英

Aggregation of different collections in MongoDB

Not sure how to do this, have a background in SQL and it is quite easier there to achieve what I need to do.

Basically I have the collection news which is like this:

const news = [
{id: '123123123', category: [ObjectID(12312312323), ObjectID(987987987)]},
{id: '123123123', category: []},
{id: '123123123', category: [ObjectID(987987987)]}
]

and then I have the collection category which is like this:

const category = [
{name: "123a", _id: ObjectID(123123123}, title:"blah blah" },
{name: "987a", _id: ObjectID(987987987}, title:"blih blah" ,
]

what I need to do is to join both tables and get an aggregation like

[
{name: "987a", title: "blih blah", count: 2},
{name: "123a", title: "blah blah", count: 1}
 
]

So even in MySQL I would get this like something similar to:

SELECT name, title, count(Select count(category) from news) from categories 

But I am not getting it with mongoDb / mongoose.

  • $lookup to join news collection, pass _id as localField and category as foreignField
  • $size to get total element count of new collection result
db.category.aggregate([
  {
    $lookup: {
      from: "news",
      localField: "_id",
      foreignField: "category",
      as: "count"
    }
  },
  { $set: { count: { $size: "$count" } } }
])

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM