There is.

/* 0 */ { "_id" : ObjectId("541c03489c3009e80de19d6b"), "ts" : 1411121993, "close" : false, "users" : [ "7e8f5f8fc847bc6", "920299d58dc02ec" ], "__v" : 0 } /* 1 */ { "_id" : ObjectId("541c035f9c3009e80de19d6c"), "ts" : 1411122016, "close" : false, "users" : [ "7e8f5f8fc847bc6", "a285496ba35fe98" ], "__v" : 0 } /* 2 */ { "_id" : ObjectId("541c035f9c3009e80de19d6d"), "ts" : 1411122016, "close" : false, "users" : [ "7e8f5f8fc847bc6", "c2f1f4e949237d1" ], "__v" : 0 } 

This is a collection of conversations.

Suppose my id is 7e8f5f8fc847bc6 .

I need to create a new dialog with user id - c2f1f4e949237d1 .

For this I need to check on the existence of such a dialogue.

If it already exists and close: false, then you need to display its dialog id, if not, create a new one.

The problem is that I do not understand how to make a verification request in mongoose.

In the users array, data can be in any order , but there can be no more than two.

In sql, it’s something like this:

 select ... where (users = ['c2f1f4e949237d1', '7e8f5f8fc847bc6'] or users = ['7e8f5f8fc847bc6', 'c2f1f4e949237d1']) and close = false 
  • @ ua6xh, thanks! - Oleg

1 answer 1

 > db.dialogs.find(); { "_id" : ObjectId("541c03489c3009e80de19d6b"), "ts" : 1411121993, "close" : false, "users" : [ "7e8f5f8fc847bc6", "920299d58dc02ec" ], "__v" : 0 } > > db.dialogs.find({users:"7e8f5f8fc847bc6", users:"920299d58dc02ec", close:false}); { "_id" : ObjectId("541c03489c3009e80de19d6b"), "ts" : 1411121993, "close" : false, "users" : [ "7e8f5f8fc847bc6", "920299d58dc02ec" ], "__v" : 0 } > > > db.dialogs.find({users:"7e8f5f8fc847bc6", users:"920299d58dc02ec", close:false},{_id:1}); { "_id" : ObjectId("541c03489c3009e80de19d6b") } > 

Upd2:

 db.dialogs.find( {$and:[ {users:"7e8f5f8fc847bc6hghg"}, {users:"920299d58dc02ec"}, {close:false} ]}, {_id:1} ); 
  • one
    Awesome! Thank! - Oleg
  • one
    @exec, I think it will be necessary to make a composite index on (users, close). In any case, it is worth creating about 1 million records and checking samples with and without an index. - Opalosolo
  • @ ua6xh, check, see. ___ @ ua6xh, stop. This search is not accurate. He searches either one by one or the other. db.dialog.find ({users: 'hjhj', users: '920299d58dc02ec'}); will find too - Oleg
  • @exec, updated the response to the new request requirements. The search is only a general coincidence. - Opalosolo
  • @ ua6xh src.unotes.ru/g/dxpsy.png - this is normal. src.unotes.ru/g/p6z14.png - this is also normal. src.unotes.ru/g/ed3ni.png - found, although it should not have been. Maybe you do not find because of the fact that one document in the collection? - Oleg