2

I need to fetch data from mongodb similer to the below sql query:

select * from ar_pages where (slug='ettarc' or id in ('1','2','3','4'))

Which uses one search condition and another with IN clause (fetch pages with specified slug and pages with list of ids)

I'm using Node Sails framework: I have tried below code: but it will not give the expected result

let listing = await Mymodel.find({
   $or: [{
      id: {
        $in: ['5cxxxx90xxxx2e23xxxxxxxx', '5cxxxx18xxxx2e81xxxxxxxx']
      }
   }, {
      user_id: 'xxxxxxxxx'
   }]
});

The above code returns below error on execution:

MongoError: $or must be an array

Mongo DB Document sample:

{
    "_id" : ObjectId("5d286f93c04a685616627095"),
    "title" : "My First Page",
    "description" : "My First Page Contents",
    "user_id" : "5c80f410c1b9eb3d8fbf541c",
    "status" : "active",
    "createdAt" : 1562931091686.0,
    "updatedAt" : 1563528420160.0,
    "is_imported" : false,
    "background_img" : "",
    "background_color" : "",
    "logo" : "",
    "media_map" : null
}
ReNiSh AR
  • 2,782
  • 2
  • 30
  • 42

2 Answers2

2

Your Query was trying to match _id without an ObjectId() wrap. You will need to wrap it up and then use it in your $in

db.ap_pages.find({
    $or: [{
        _id: {
            $in: [ObjectId('5d3595d9022a3de52f62ce79'), ObjectId('5d3595d9022a3de52f62ce7d')]
        }
    }, {
        user_id: '5c80f410c1b9eb3d8fbf541d'
    }]
});

To find that doc using Mongoose, you'd have to define _id in the schema for ap_pages as:

_id: { type: String }

and simply use it

db.ap_pages.find({
        $or: [{
            _id: {
                $in: ['5d3595d9022a3de52f62ce79', '5d3595d9022a3de52f62ce7d']
            }
        }, {
            user_id: '5c80f410c1b9eb3d8fbf541d'
        }]
    });
1

Try this

db.ar_pages.find({

    "$or": [{
        "slug" : 'ettarc' 
    },{ "id": {"$in":  ['1','2','3','4']}
    }]
});

For Sails Framework use this:

db.ar_pages.find({
    or: [
       { 
          "slug" : 'ettarc' 
       }, {
          "id": {
             in:  ['1','2','3','4']
          }
       }
    ]
});
ReNiSh AR
  • 2,782
  • 2
  • 30
  • 42
James
  • 1,819
  • 2
  • 8
  • 21
  • Tried this, but return error: MongoError: $or must be an array – ReNiSh AR Jul 22 '19 at 07:13
  • Work for me when change $ sign. $ is not used in sails frame sork (sails mongo) for in and or operator. Instead of using $or and $in simply use or and in – ReNiSh AR Jul 23 '19 at 06:04