website icon indicating copy to clipboard operation
website copied to clipboard

WHERE Query on JSON datatype

Open saurabhverma2892 opened this issue 9 years ago • 10 comments

Hey,

I have a column which is JSON datatype and contains Id, Email, etc inside it in the form of json I am trying to get a user from the database where facebook.id = "some value"

User.find({where:{'facebook.id': profile.id}})

but this gives a syntax error: Executing (default): SELECT _id, name, email, role, password, provider, salt, facebook, twitter, google, github, createdAt, updatedAt FROM users AS User WHERE (User.facebook#>>'{id}') = '1239871587612' LIMIT 1; SequelizeDatabaseError: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

I guess the error is at the syntax used at { 'facebook.id': profile.id}.

How can we query on the parameters inside JSON?

a raw query for the same which works looks like: SELECT name from users As User WHERE facebook->"$.id" = "1239871587612”;

possible solutions?

saurabhverma2892 avatar Apr 18 '16 12:04 saurabhverma2892

As you've noticed, JSON is currently only supported in postgres https://github.com/sequelize/sequelize/issues/4727

janmeier avatar Apr 18 '16 12:04 janmeier

Possible workaround? or can i do a raw query for this?

saurabhverma2892 avatar Apr 18 '16 12:04 saurabhverma2892

Completely raw query yes, or you could use literal:

User.findAll({
  where: {
    $and: [
      sequelize.where(
        sequelize.literal('facebook->"$.id"'),
        "1239871587612"
      )
    ]
  }
});

(this example shows how the condition might be combined with other, regular where clauses - if you dont need that you can simply do where: sequelize.where...)

janmeier avatar Apr 18 '16 12:04 janmeier

@janmeier Works! Thanks! :)

saurabhverma2892 avatar Apr 18 '16 13:04 saurabhverma2892

Just for information JSON type is supported in MySql 5.7

Demonium avatar May 06 '16 07:05 Demonium

@Demonium yes it is. but not supported by sequelize for mysql

saurabhverma2892 avatar May 06 '16 09:05 saurabhverma2892

        (where: {
            country: {
                '"state"': {
                    '"city"': {
                        $eq: 'Mumbai'
                    }
                }
            }
        });

This worked for me, 3 layers in the JSON object

pratik-freightwalla avatar Sep 25 '19 06:09 pratik-freightwalla

This probably deserves to be better explained in the docs :)

papb avatar Oct 06 '19 15:10 papb

Any news?

mahnunchik avatar Mar 12 '20 19:03 mahnunchik

where: {
  facebook: {
     id: profile.id
  }
}

assuming facebook is an object and profile.id is the value which you want to query, this should work

sharadshetty2 avatar Aug 13 '20 07:08 sharadshetty2