mongodb query result sequence - mongodb

Here is my query statement.
db.users.find({"_id":{"$in":[id0, id1, id2]}})
Of course it will return correct user array, but the sequence is random, it could be
[user1, user0, user2]
or
[user2, user0, user1]
it depends on ids' value.
If there is a way that I could force mongodb always return user array like this
db.users.find({"_id":{"$in":[id0, id1, id2]}}) => [user0, user1, user2]
db.users.find({"_id":{"$in":[id1, id0, id2]}}) => [user1, user0, user2]

I don't know if the query syntax supports that (I wouldn't think so), but you can always post-process the results to hash them by lookup id

Related

In MongoDB how to decide for a collection which fields to be indexed for a costly query

I have a collection with 1000+ records and I need to run the query below. I have come across the issue that this query takes more than a minute even if the departmentIds array has length something like 15-20. I think if I use an index the query time will be reduced.
From what I observe the 99% of the time spent on the query is due to the $in part.
How do I decide which fields to index. Should I index only department.department_id since that's what taking most time or should I create a compound index using userId,something and department.department_id (bascially all the fields I'm using in the query here)
Here is what my query looks like
let departmentIds = [.......................... can be large]
let query = {
userId: someid,
something: something,
'department.department_id': {
$in: departmentIds
}
};
//db query
let result = db
.collection(TABLE_NAME)
.find(query)
.project({
anotherfield: 1,
department: 1
})
.toArray();
You need to check all search cases and create indexes for those that are often used and most critical for your application. For the particular case above this seems to be the index options:
userId:1
userId:1,something:1
userId:1,something:1,department.department_id:1
I bet on option 1 since userId sounds like a unique key with high selectivity very suitable for index , afcourse best is to do some testing and identify the fastest options , there is good explain option that can help alot with the testing:
db.collection.find().explain("executionStats")

How to sort a collection by row in MongoDB?

I am using MongoDB with hapi.JS. I have a collection which contains few rows in the schema. I want to sort the rows in either asc order or desc order but want to mention it in the URI. for example the URI should look something like this
/api/v1/customers?sort=name&direction=asc&limit=30
How can I sort this collection by asc or desc order and limit can be fixed or flexible as well.
I have defined like this as of now but even if I mention the sort in URI it gives the output only in asc order.
Models.Account.find(criteria,projection,{skip:5,limit:5},function(err,resp){
if(err)
callbackRoute(err);
else
callbackRoute(err,resp);
}).sort({[_id]:"asc"});
db.yourcollection.find(...).sort({ name:1 }).limit(30)
or with dynamic values:
// following is ECMA 6 only
// get params and make sure values are what you expect (check for injection) + direction must be = "asc" || "desc"
db.yourcollection.find(...).sort({ [sort]: direction }).limit(30)

Sorting with a ReactiveMongo JSON query

This seems crazy that I have to ask but I cannot find the right syntax to sort query result using ReactiveMongo. So if I had this:
rCollection.flatMap(
// find all
_.find(Json.obj())
// perform the query and get a cursor of JsObject
.cursor[Resort](ReadPreference.primary)
// Collect the results as a list
.collect[List](Int.MaxValue, Cursor.FailOnError[List[Resort]]())
)
How would I sort by a particularly column in descending order.
This would probably be:
rCollection.flatMap(
// find all
_.find(Json.obj())
.sort(Json.obj())
// perform the query and get a cursor of JsObject
.cursor[Resort](ReadPreference.primary)
// Collect the results as a list
.collect[List](Int.MaxValue, Cursor.FailOnError[List[Resort]]())
)
The JSON object you send to the 'sort' function would be the same JSON you'd use in mongo query for sorting. eg:
{"age": 1, "lastName": -1}
sorts by age ascending and then lastName descending.

how to query to a collection with array in mongodb

I Have An Array With 4 Object Items I want query to my collection and return 4 items that have this uid's...
myArray = > [{uid : 'test'},{uid : 'test2'},{uid : 'test3'},{uid : 'test4'}]
ProductCollection.find({????},(err,result)=>{})
NOTE : I dont want use any loop
I dont want use any loop
I will assume that's related to query the DB several times, one for each uid value.
Anyway, you can go to the database once to filter elements that match an array of values, like your case, using MongoDB's $in operator.
But you would have to format the uid values to an array of the values themselves instead of the array of objets, this can be accomplished with a simple .map call (don't know if you will consider this a loop) to get the filter value in the correct format.
var uids = myArray.map((item) => item.uid })
// ['test', 'test2', 'test3', 'test4']
And after that you can query your DB with this uids values
ProductCollection.find({'uid': {'$in': uids} },(err,result)=>{})
(Assuming 'uid' it the property you have in your ProductCollection that you are trying to filter by)

mongoskin select special fields rather than all

I'm looking for a way to get special fields from mongoskin find function. in other words in SQL lang we say select column1,column2,column3 from mytable rather than select *
currently my query is like below and i want to get specify the fields that I'm looking for rather the the whole json object.
db.collection('collacta').find().toArray(function(err, result) {
if (result) {
...
} else {
...
};
});
thanks
For getting the projection of fields, you should pass the DBObject for projection,
DBCursor cursor = collection.find(query, projectionQuery);
The projection is The DBObject in form of key-value pair. where,
key is the name of field you want to project. value can be either 0 or 1.
0 - means exclude the particular column from result set.
1 - means include the particular column in result set.
For more info, see here.