0

I have a mongodb-realm object(collection) named 'Products':

THE SCHEMA:

const Products = {

  name: "Products",

  properties: {

      _id: "objectId",
      name : "string",
    }
}

THE DATA

_id:'60f73ca7c1a70278596cc7d0',
products:[
      {_id:1, name: 'product1'},
      {_id:2, name: 'product2'},
      {_id:3, name: 'product3'},
      {_id:4, name: 'product'}
]

Now, I want to select some(say two) of these using realm. In this case I want to filter product1 and product2. I'm trying to put the ids in an array and try to filter them but it doesn't work. Below is my code

const obj = realm.objects('Products').filtered("_id == $0", [ObjectId('1'), ObjectId('2')])

Now My question is: How can I filter multiple rows in realm? And as my example above, how can I filter product1 and product2?

Amani
  • 227
  • 1
  • 10
  • Realm has no rows, only objects. Not sure of your coding platform and when you query Realm, it does not return an array, it returns a Results object. It's similar to an array but there are some important differences (lazy loading, live updating etc). If you know the specific object you want, you can read it directly via the [Read object by Primary Key](https://docs.mongodb.com/realm/sdk/react-native/examples/read-and-write-data/#find-a-specific-object-by-primary-key) - that's faster than a query. You can combine those into single statement with OR – Jay Feb 03 '22 at 17:16
  • Oh it's not clear how the item `_id` is being populated (1, 2, 3 is a little odd), but if your _id's are strings, you will need to filter them as strings; `.filtered('_id == $0', ['1', '2']);` likewise, if they are Int's (which they appear to be) you'll need to filter as Int's. – Jay Feb 03 '22 at 21:10
  • @Jay the _ids ['1','2'] is just for illustation only when asking the question. In reality on my code they are ObjectId's. ie ["61fe2d7638fbf4022f984927","61fe2d6438fbf4022f984920"]. – Amani Feb 05 '22 at 08:00
  • @Jay when using ```.filtered('_id == $0', ["61fe2d7638fbf4022f984927","61fe2d6438fbf4022f984920"])``` like you've showed me on your comment, it doesn't work. It gives this Error: ```Error: Unsupported comparison between type 'objectId' and type 'link'``` – Amani Feb 05 '22 at 08:03
  • And not to forget mentioning: I AM USING REALM JAVASCRIPT – Amani Feb 05 '22 at 08:14
  • 1
    Please remember to TAG YOUR QUESTION WITH YOUR CODING PLATFORM so it gets users with that experience looking at your question. See my answer [here](https://stackoverflow.com/questions/69286354/how-to-see-if-realm-objectid-equals-string-javascript) – Jay Feb 05 '22 at 16:17

0 Answers0