Skip to content

Embedded Documents (Dealing with Arrays and Objects)

  • Find comments whose user is Lily.
shop> db.comments.find({'comments.user': 'Lily'})
[
  {
    _id: 6,
    title: 'Schema Design Best Practices',
    content: 'Designing schemas for optimal performance...',
    author: 'Emily Brown',
    comments: [
      { user: 'Kevin', text: 'Invaluable insights!' },
      { user: 'Lily', text: 'Well-structured explanations.' }
    ],
    metadata: { views: 700, likes: 65 }
  }
]
  • Find documents whose views in metadata is greater than 1200
shop> db.comments.find({'metadata.views': {$gt: 1200}})
[
  {
    _id: 4,
    title: 'Advanced Queries in MongoDB',
    content: 'Learn how to write complex queries...',
    author: 'Michael Johnson',
    comments: [
      { user: 'Grace', text: 'Mind-blowing content!' },
      { user: 'Henry', text: 'Impressive examples.' }
    ],
    metadata: { views: 1500, likes: 60 }
  }
]

$all

  • $all operator is used to find elements that contains all the values given in the array.
shop> db.comments.find({"comments.user": {$all: ["Alice", "Vinod"]}})
[
  {
    _id: 7,
    title: 'Introduction to MongoDB',
    content: 'MongoDB is a popular NoSQL database...',
    author: 'Vinod Thapa',
    comments: [
      { user: 'Alice', text: 'Awesome article!' },
      { user: 'Vinod', text: 'Thanks for sharing.' }
    ],
    metadata: { views: 1000, likes: 70 }
  }
]

$elemMatch

  • Find all the documents that satisfies the given query
  • In simple words, to perform AND operation in the embedded documents.
shop> db.comments.find({"comments": {$elemMatch: {"user": "Vinod", "text": "Thanks for sharing."}}})
[
  {
    _id: 7,
    title: 'Introduction to MongoDB',
    content: 'MongoDB is a popular NoSQL database...',
    author: 'Vinod Thapa',
    comments: [
      { user: 'Alice', text: 'Awesome article!' },
      { user: 'Vinod', text: 'Thanks for sharing.' }
    ],
    metadata: { views: 1000, likes: 70 }
  }
]