Valentin H
Valentin H

Reputation: 7458

Find object with value in its array

I'm using lokijs, which has "mongo-similar" query language.

devices.insert({key:'d1', name:'Device1', users:['u1'], status: 'OK', current_wl:'123'})
    devices.insert({key:'d2', name:'Device2', users:['u1','u1'], status: 'OK', current_wl:'123'})
    devices.insert({key:'d3', name:'Device3', users:['u2','u3'], status: 'OK', current_wl:'123'})
    devices.insert({key:'d4', name:'Device4', users:['u1','u2','u3','u4'], status: 'OK', current_wl:'123'})

My attempt to find a device having user 'u1' in its array users returns emty list:

a= devices.find( {users:{ "$in" : ["u1"] }}  )
console.log("A", a);

Is the query correct, if the problem was for mongodb? Is there another way to do it in mongo? Is there another way to do it in lokijs?

Upvotes: 1

Views: 252

Answers (2)

Valentin H
Valentin H

Reputation: 7458

I found a solution (or a work-around) using where:

a= devices.where( function(obj){
      return obj.users.indexOf('u1') > -1;
   }
);

Upvotes: 1

Lex
Lex

Reputation: 184

I'm not sure about lokijs, but that's the correct query in Mongo.

If you're only ever going to query for documents that contain a single specific item in their "users" array, a simpler query for this case in Mongo would be:

db.collection.find({ users: "u1" })

Upvotes: 1

Related Questions