0

I want to get chat histories on mongodb.So I need use logical query in mongodb.
I have a message object.And Message have to,sender and message.

For example; in mongodb:

-->to: A sender: B message: blabla
-->to: B sender: A message: blahblah
-->to: C sender: A message: haha

I need only speech between A and B limit last 20.How can I do that in node.js?

My code:

function getLastMessageFor(to,sender){
  MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
    if (err)
      throw err;
    console.log("Connected to Database");

    db.collection('test').find($or :[ $and[{"to":to},{"sender":sender}], $and[{"to":sender},{"sender":to}]]).limit(..){})
  });
}

To me, ı need {(to = toName AND sender = senderName) OR (to = senderName AND sender = toName)}.last(20) the logic of this. But how can I do that in mongodb into nodejs. I need speech between A and B last 20.

1
  • Im sorry,copy paste problem.I have written dirty code so I didn't try yet.if you understand this logic,can you write 'find()' codes completely to here? Commented Aug 29, 2014 at 19:09

1 Answer 1

1

It seems you're very close, just clean it up a bit to be:

db.collection('test').find({$or: [
    {"to": to, "sender": sender},
    {"to": sender, "sender": to}
]}).limit(20).toArray(function(err, messages) {
    console.log(messages);
});

There's an implicit $and among fields in the same query object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.