简体   繁体   中英

Mongo db query all documents contains substring matching in a given array of strings

The title might be a little confusing, here is the data:

location_collection:

{name: "A"}
{name: "A1"}
{name: "B"}
{name: "B1"}
{name: "C"}
{name: "C1"}

my query:

 mongooseModel.find({ name: { $in: ['A', 'B'] } })

what I get:

{name: "A"}
{name: "B"}

What I want to get:

{name: "A"}
{name: "A1"}
{name: "B"}
{name: "B1"}

I try this but it doesnt work:

 mongooseModel.find({ name: { $in: [$substr:['A'], $substr:['B']] } })

Thanks in advance.

You can use $regex

db.collection.find({
  $or: [
    {
      name: {
        $regex: "A",
        
      }
    },
    {
      name: {
        $regex: "B",
        
      }
    }
  ]
})

Mongo playground: https://mongoplayground.net/p/BMV2oNDjp-1

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