Mongo, find through list of ids - mongodb

I have a process that returns a list of String MongoDB ids,
[512d5793abb900bf3e20d012, 512d5793abb900bf3e20d011]
And I want to fire a single query to Mongo and get the matching documents back in the same order as the list.
What is the shell notation to do this?

After converting the strings into ObjectIds, you can use the $in operator to get the docs in the list. There isn't any query notation to get the docs back in the order of your list, but see here for some ways to handle that.
var ids = ['512d5793abb900bf3e20d012', '512d5793abb900bf3e20d011'];
var obj_ids = ids.map(function(id) { return ObjectId(id); });
db.test.find({_id: {$in: obj_ids}});

This works fine for me in Robo 3T. No need to create any object and just use the list of ids.
db.getCollection('my_collection').find({'_id':{$in:['aa37ba96']}})

// categoryId comma separated "5c875c27d131b755d7abed86,5c875b0ad131b755d7abed81" in request
var ids= req.body.categoryId.split(',');
db.test.find({ categoryId: { $in: ids } });

If your final purpose is to get the document with the order by your pre-get ids list, you can just convert the query result into mapping(id as key, doc as value) , and then traverse the ids list to get the doc.

Related

Return array of arrays as response from query in mongoose

I am working with a query in mongoose as below:
return await this.model.find({ lastname: req.lastname})
(lastname is a field in my collection)
Everything works fine, but I need a way to get the data from the query in this kind of structure:
[ [data], [data] ...., [data]]
Currently I am getting this kind of response: [ {data}, {data}....., {data}].
I have a solution for you. First of all, what you are doing is simply getting the result in default format.
In order to get the solution in your required format,
Use array, $push and $each.
**Array:** First, make sure that you create a result array
let result = [];//create an array
result = await db.find({filter}.$push({$each()});

find data with arrays of ids in mongodb?

I have a array list from another example but this don’t work for me, maybe is because i need use ObjectId()’ but i don’t know how i will can parse this array, too i don’t know if is possibly get only once param (username) and not the full array?
the code is this:
var list = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"]
.find({ _id: {$in : list}},{username:1})
can you help and say me how i need create the query ? 🙏🏻 thanks.
You query is correct except you need to wrap your ids inside ObjectId using map.
var ObjectId = require('mongodb').ObjectID
var list = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"]
db.collectionName('newCollection').find({ _id: {$in : list.map( (id) => ObjectId(id))}}, {userName:1, _id:0})

How to query all documents user has access to in mongodb?

I am trying to figure out how to display all documents user has access to but i am either getting no documents at all or undefined user.docs if person is not logged in.
In Meteor, my user has
docs: {
"xxx1",
"xxx2",
"xxx3"
}
etc (it may be limitless number of ids.
How to query mongo to find all documents that have id = user.docs? (return array of docs).
'If a person is not logged in'? I'm assuming this is server side?
Are you trying to grab 'docs' off of Meteor.user() ?
That only works on the current logged in user.
Server side mongodb query on a user:
Meteor.users.findOne({_id: '<userId string here>'},{fields: {docs: 1}});
Should give you:
{_id: '<userId string here>', docs: {...docs here...}}
Be careful with user data!
EDIT:
If you are trying to get docs that match the doc ids from a user object, you would ideally rearrange your data structure to
docs: ['docId', 'docId'] <---this may be your main problem
Then it would be:
var userDocsIds = Meteor.users.findOne({_id: '<userId string here>'},{fields: {docs: 1}});
var userDocs = Docs.find({_id: {$in: userDocsIds.docs}}).fetch();
Use the $in operator to find _ids in an array:
const docIds = Meteor.users.findOne(id).docs;
const myDocs = Docs.find({_id: {$in: docIds }});
i have tried both and ended up using
docs = getDocsForUser(user); //print array of docs
return docs.find({_id: {$in: docs}})

Using "$and" and "$in" together

I have a collection friends which i am using to store all the friends and has the following fields
id , userid, friendid
I have a collection notes which stores user notes and has the following fields
id, userid , ownerid , privateorpublic
The rule is a user can only see notes he/she has created or notes created by his/her friends or notes that are public
To fetch that information i am writing my query this way. First, get all the ids of my friends separated by a comma. I dont know how to write the query to return comma delimited values but this query below I am hoping will return all the firneds of the user by the given id:
db.friends.find({ { friendid: { userid: 'jhdshh37838gsjj' } }
then get the notes where are either created by a friend or are public notes or are notes belonging to user
db.notes.find({ownerid:'jhdshh37838gsjj', privateorpublic:'public',{ $in: [ "3ghd8e833", "78hhyaysgd" ] }
I am new to MongoDB. Are my queries right?
Find query syntax : db.collection.find({queryFieldName: queryFieldValue}, {requiredFieldName: 1, NotRequiredFieldName: 0})
Thus, translating first query, you'd get "get me all documents from collection friends where friendId equals a string {'userId':'Id'}" which is not desired.
Query for "Get me all friend Ids of userid jhdshh37838gsjj and don't print anything else in results" : db.collection.find({userId:'jhdshh37838gsjj'}, {friendId:1, _id:0})
However, this'll not give output as comma separated values. You'll get output as follows (because every document is an independent object):
{friendId: 1}
{friendId: 2}
$in requires array as input and not comma separated values. To make an array of field values for a $in query, you need to some extra work like:
var friendIdsArr = [] //Initiate an array to store friend Ids
db.friends.find({'userId':'jhdshh37838gsjj'},{'friendId':1,'_id':0}).forEach(function(x) {friendIdsArr.push(x.friendId);} ); //Foreach result in query, push value to array.
The friendIdsArr will be [1,2]
db.notes.find({'ownerId':'jhdshh37838gsjj', 'privateOrPublic':'public',{$in: ["friendId": friendIdsArr]})
will give results, json documents, matching the given conditions.
Interestingly, your notes collection doesn't have a note field.
I'd recommend you to read mongodb official documentation and make a single query instead of two different queries.

Mongodb find() don't work

Why dosen't db.find work? The console.log gets undefined...
var course = (db.courses.find({ _id: mongo.helper.toObjectID(param.course)}));
console.log(course.body)
The way you are trying use Selects documents in a collection and returns a cursor to the selected documents., so you can't use the way you are trying to use it.
You need to use a callback() to get the records matching the query.
The below code will give result in an array format :-
db.courses.findOne({ _id: mongo.helper.toObjectID(param.course)}).toArray(function(err, result)
{
console.log(result[0]); // will give you the matched record.
})