How to query two collections that have a "one-to-many" relationship in MongoDB?

Kiten

We have two collections: "houses" and "events". Each document in the houses collection contains an "events" field with an array of id's that refer to events (a "one-to-many" relationship). The array can be empty.

"House" schema:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const HouseSchema = new Schema({
  name: String,
  district: String,
  locality: String,
  date: {
    type: Date,
    default: Date.now
  },
  events: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Event'
  }]
});

module.exports = mongoose.model('House', HouseSchema);

"Event" schema:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const EventSchema = new Schema({
  event: String,
  details: String,
  date: {
    type: Date,
    default: Date.now
  },
  house: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'House'
  }
});

module.exports = mongoose.model('Event', EventSchema);

I need to query both "houses" and "events" and find those "houses" with referred "events" that meet all the criteria. I will give several options for queries.

Query with parameters only from "houses". Let's say there are two docs in the "houses" collection that satisfy the condition {"locality": "Facebook"}. The result should be like this:

[
  {
    "_id": "601bae8e26ed00591d571dbe",
    "name": "Facebook testing department",
    "district": "Los-Angeles",
    "locality": "Facebook",
    "events": [
      {
        "_id": "601bae8e26ed00591d571dbf",
        "event": "Testing",
        "details": "Testing software for production",
        "date": "2020-07-31T21:00:00.000Z"
      }
    ]
  },
  {
    "_id": "601bae8e26ed00591d571dbc",
    "name": "Facebook office",
    "district": "Los-Angeles",
    "locality": "Facebook",
    "events": [
      {
        "_id": "601bae8e26ed00591d571dbd",
        "event": "Conference",
        "details": "Developers conference about 12345",
        "date": "2020-07-31T21:00:00.000Z"
      }
    ]
  },
];

Query with parameters only for "events". Let's say there are two records in the "events" collection that satisfy the condition {"event": "Conference"}. The result is:

[
  {
    "_id": "601bae8e26ed00591d571dbc",
    "name": "Facebook office",
    "district": "Los-Angeles",
    "locality": "Facebook",
    "events": [
      {
        "_id": "601bae8e26ed00591d571dbd",
        "event": "Conference",
        "details": "Developers conference about 12345",
        "date": "2020-07-31T21:00:00.000Z"
      }
    ]
  },
  {
    "_id": "601bae8e26ed00591d571dba",
    "name": "Oxford",
    "district": "London",
    "locality": "Oxford",
    "events": [
      {
        "_id": "601bae8e26ed00591d571dbb",
        "event": "Conference",
        "details": "About something",
        "date": "2020-07-31T21:00:00.000Z"
      }
    ]
  },
];

Query with parameters for both "houses" and "events". If the criteria of our query is {"locality": "Facebook", "event": "Conference"}, then the result should be like this:

[  
  {
    "_id": "601bae8e26ed00591d571dbc",
    "name": "Facebook office",
    "district": "Los-Angeles",
    "locality": "Facebook",
    "events": [
      {
        "_id": "601bae8e26ed00591d571dbd",
        "event": "Conference",
        "details": "Developers conference about 12345",
        "date": "2020-07-31T21:00:00.000Z"
      }
    ]
  },
];

I have faced similar situations where it is necessary to make queries more complex than usual. But here we need to make a query - depending on the parameters - for one or two collections, and as a result, we should get "houses" with nested "events" that correspond the query parameters. I don't know MongoDB aggregation that well, would appreciate any help.

turivishal
  • Declare your inputs
let locality = req.body.locality;
let event = req.body.event;
  • Initialize aggregation pipeline (replace HousesModel to your reql model name)
let p = HousesModel.aggregate();
  • Check condition for locality
if (locality && locality.trim()) p.match({ locality: locality });
  • $lookup with pipeline,
  • declare events array into let
  • match events condition in expression
  • check condition if events search is available then put condition
p.lookup({
  from: "events", // replace your actual collection name if this is wrong
  let: { events: "$events" },
  pipeline: [
    {
      $match: {
        $and: [
          { $expr: { $in: ["$_id", "$$events"] } },
          (event && event.trim() ? { event: event } : {})         
        ]
      }
    }
  ],
  as: "events"
});
  • make sure events is not empty
p.match({ events: { $ne: [] } });
  • execute above pipeline
let result = await p.exec();

Playground

Combine above code in sequence and test.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Have two entity in Grails with one to many relationship

From Dev

Query two tables with one to many relationship

From Dev

How to update a one to many relationship MongoDB

From Dev

How to query one-to-many relationship in JPQL?

From Dev

How to serialize entities that have a one-to-many relationship with Entity Framework?

From Dev

Ideas how to query two collections in mongodb

From Dev

Query One to Many Relationship SQLAlchemy

From Dev

JPA one to many relationship query

From Dev

Django query in One to Many relationship

From Dev

Django one to many Relationship Query

From Dev

Query One to Many Relationship SQLAlchemy

From Dev

Two way one to many relationship

From Dev

How to query a one to many/many to many relationship in Flask SQL Alchemy?

From Dev

How to use a subquery to filter a sqlalchemy query on a one to many relationship?

From Dev

How to query with one to many?

From Dev

How to implement one to many relationship

From Dev

Two mongodb collections in one query

From Dev

MongoDB Show children items in One to Many relationship

From Dev

CoreData: Query to one-to-many-to-many relationship

From Dev

Criteria query for unidirectional one-to-many relationship

From Dev

jooq single query with one to many relationship

From Dev

Data base One To Many Relationship Query

From Dev

Data base One To Many Relationship Query

From Dev

query regarding one to many relationship in hibernate

From Dev

Criteria query for unidirectional one-to-many relationship

From Dev

Ruby on Rails Query a one to many relationship

From Java

How to group two collections in one query with MongoDB or Mongoose

From Dev

One to Many Relationship (or NoSQL Mongo equivalent to it) in Meteor Collections

From Dev

Android ListView: how to avoid database query in bindView()? Need to fetch one to many relationship data

Related Related

  1. 1

    Have two entity in Grails with one to many relationship

  2. 2

    Query two tables with one to many relationship

  3. 3

    How to update a one to many relationship MongoDB

  4. 4

    How to query one-to-many relationship in JPQL?

  5. 5

    How to serialize entities that have a one-to-many relationship with Entity Framework?

  6. 6

    Ideas how to query two collections in mongodb

  7. 7

    Query One to Many Relationship SQLAlchemy

  8. 8

    JPA one to many relationship query

  9. 9

    Django query in One to Many relationship

  10. 10

    Django one to many Relationship Query

  11. 11

    Query One to Many Relationship SQLAlchemy

  12. 12

    Two way one to many relationship

  13. 13

    How to query a one to many/many to many relationship in Flask SQL Alchemy?

  14. 14

    How to use a subquery to filter a sqlalchemy query on a one to many relationship?

  15. 15

    How to query with one to many?

  16. 16

    How to implement one to many relationship

  17. 17

    Two mongodb collections in one query

  18. 18

    MongoDB Show children items in One to Many relationship

  19. 19

    CoreData: Query to one-to-many-to-many relationship

  20. 20

    Criteria query for unidirectional one-to-many relationship

  21. 21

    jooq single query with one to many relationship

  22. 22

    Data base One To Many Relationship Query

  23. 23

    Data base One To Many Relationship Query

  24. 24

    query regarding one to many relationship in hibernate

  25. 25

    Criteria query for unidirectional one-to-many relationship

  26. 26

    Ruby on Rails Query a one to many relationship

  27. 27

    How to group two collections in one query with MongoDB or Mongoose

  28. 28

    One to Many Relationship (or NoSQL Mongo equivalent to it) in Meteor Collections

  29. 29

    Android ListView: how to avoid database query in bindView()? Need to fetch one to many relationship data

HotTag

Archive