Home > Mobile >  how to find if a field contains a string in a field from mongoDB
how to find if a field contains a string in a field from mongoDB

Time:08-17

I have a problem that I can get a data from mongoDB but it's not what i want.

I just want to get a data, if datas have "#l" sting in the message field, I want it.

here's data on mongodb

({...someData, message: 'asdfff #lol blah blah blah hellohellohellohello'})
({...someData, message: '#lol asdfff blah blah blah byebyebye'})
({...someData, message: 'asdfff asdffasfdah blah blah #lol hello'})
({...someData, message: 'asdfff #l blah blah blah hello'})
({...someData, message: 'asdfff #lo blah blah blah hello'})

here's what i've done

const hashtagPosts = await Post.aggregate([
      {
        $match: {
          message: { $regex: `#${hashtag}` },
        },
      },
      {
        $sort: {
          createdAt: -1,
        },
      },
      {
        $limit: 10,
      },
    ]);
    const hashtagPosts = await Post.find({
      message: { $regex: `#${hashtag}` },
    });

and If I run these code with "#l" this hashtag I will get this data

({...someData, message: 'asdfff #lol blah blah blah hellohellohellohello'})
({...someData, message: '#lol asdfff blah blah blah byebyebye'})
({...someData, message: 'asdfff asdffasfdah blah blah #lol hello'})
({...someData, message: 'asdfff #l blah blah blah hello'})
({...someData, message: 'asdfff #lo blah blah blah hello'})

What I want, the result

({...someData, message: 'asdfff #l blah blah blah hello'})

if I search with "#l" this searchword I want to get datas that contain exact the same searchword like "#l" => "#l"

not contain "#lol" "#lo" is it possible? I have no idea how can i get datas like that. thanks for reading my question.

CodePudding user response:

You just need to change your regex, if you want to allow any match precending #l except a letter you could use the negative lookahead syntax like Output

CodePudding user response:

You can do it like this way.

const hashtagPosts = await Post.find({
      message: /#l/i
    });

Another way to do this.

const hashtagPosts = await Post.find({
      message:  { "$regex": "#l", "$options": "i" }
    });
  • Related