search

Home  >  Q&A  >  body text

mongodb - Requirements for statistical query of mongoose related tables

I want to ask a question about mongodb (mongoose).
A blog has two tables, articles and tags, a many-to-many relationship.
The tag field in the article table is an array, which stores the tags. id, when querying articles, the data of each tag can be associated.
The current demand is:
Query tag When making a list, you need to get at the same time how many articles each tag is included in, that is, count.
In addition to traversing and manually establishing the count field and re-counting when adding, deleting, or modifying the count field
Is there a better way to achieve it through the mongoose API? Method, thank you all!

为情所困为情所困2784 days ago1046

reply all(2)I'll reply

  • PHPz

    PHPz2017-05-02 09:26:37

    Solved, aggregation query is required. Decompose before aggregation, and then aggregate. Specific code. In fact, aggregation query itself can query requirements, but the requirements are many-to-many data relationships, not one-to-many, so they must be decomposed into one-to-one first. Relationship

    Related code snippets
    Related reference documents

    // 查询article-tag的count聚合数据
      const getTagsCount = tags => {
        let $match = {};
        if (!authIsVerified(req)) {
          $match = { state: 1, public: 1 };
        }
        Article.aggregate([
          { $match },
          { $unwind : "$tag" }, 
          { $group: { 
            _id: "$tag", 
            num_tutorial: { $sum : 1 }}
          }
        ])
        .then(counts => {
          const newTags = tags.docs.map(t => {
            const finded = counts.find(c => String(c._id) === String(t._id));
            t.count = finded ? finded.num_tutorial : 0;
            return t;
          });
          tags.docs = newTags;
          querySuccess(tags);
        })
        .catch(err => {
          querySuccess(tags);
        })
      };

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-02 09:26:37

    There is a very useful tool called Population in mongoose. Please check it out

    reply
    0
  • Cancelreply