Try: MongoDB Regular Expresssions

^ : starts with

$ : Ends with

.* : any char, any number of times

/i : case insensitive

Try the following Queries

•db.posts.find( { title: { $regex: /4$/ } } );

•db.posts.find( { category: { $regex: /^T.*/ } } );

• db.posts.find( { category: { $not: /^p.*/ } } );

•db.posts.find( { category: { $regex: /^ev/i } } );

•db.posts.find( { category: { $regex: /^ev/ } } );

•db.posts.find( { category: { $regex: /^Ev/ } } );

•db.posts.find( { category: { $regex: /^Ev.*t$/ } } );

•db.posts.find( { category: { $regex: /^Ev*t$/ } } );

Use Data from the Following URL:

https://www.w3schools.com/mongodb/mongodb_mongosh_insert.php

db.posts.insertMany([  
  {
    title: "Post Title 2",
    body: "Body of post.",
    category: "Event",
    likes: 2,
    tags: ["news", "events"],
    date: Date()
  },
  {
    title: "Post Title 3",
    body: "Body of post.",
    category: "Technology",
    likes: 3,
    tags: ["news", "events"],
    date: Date()
  },
  {
    title: "Post Title 4",
    body: "Body of post.",
    category: "Event",
    likes: 4,
    tags: ["news", "events"],
    date: Date()
  }
])

Leave a Reply