How to select two different values for one selector with a limit?


#1

I’m not sure what the proper word to describe. I want to do something like this:

var room1 = 'xyz',
      room 2 = 'abc';

Message.find({room:room1},{fields:{message:1, room:1}},{limit:1});
Message.find({room:room2},{fields:{message:1, room:1}},{limit:1});

How can I do this in a single query? I tried the following and it didn’t work

rooms = ['xyz', 'abc'];
Message.find({room:{$in:rooms}},{fields:{message:1,room:1}},{limit:1});

Please help me! Urgent! Thanks in advance!


#2

I think what you want is a $or

Message.find({$or:[{room:room1}, {room:room2}]},{fields:{message:1, room:1}, limit:1});

#3

I tried and I got

"Can't canonicalize query: BadValue unknown operator: $or"

I need messages from room1 with limit 1 and messages from room2 with limit 1.


#4

I fixed my previous post… When I copied your query I had not noticed that you had split your limit into a third parameter so I’ve changed that to reflect the correct syntax.

As for the error, I have no Idea why it would give that since the query filter is valid.

If you need one message from each room you will likely need to use 2 separate queries. There may be a way to do this with mongo’s aggregation pipeline, but you will only be able to use that on the server and I personally do not know enough of about the aggregation pipeline to say what you could accomplish.

If you go with 2 separate queries though, remember to fix your limit so that you actually only get back 1 from each room.


#5

Thanks for helping! I guess I will have to do aggregation then.