Mongoid: Find Through Array of Ids

Mongoid: find through Array of ids

You can do the ordering by hand after you have all your objects. Something like this:

ordering = { }
ids.each_with_index { |id, i| ordering[id] = i }
objs = MyModel.find(ids).sort_by { |o| ordering[o.id] }

Retrieving array of ids in Mongoid

Remember that the ID is stored as :_id and not :id . There is an id helper method, but when you do queries, you should use :_id:

User.where(:_id.in => arr)

Often I find it useful to get a list of ids to do complex queries, so I do something like:

user_ids = User.only(:_id).where(:foo => :bar).distinct(:_id)
Post.where(:user_id.in => user_ids)

Mongoid Search by Array of Association Id's

If the relations are

Customer has_many :branches and

Branch belongs_to :customer,

Then branches collection will have a customer_id column and not the reverse. So you can do

cust_ids = Branch.where(name: "New York").map(&:customer_id)
Customer.find(cust_ids)

Since you need only the customer ids from the first query, it is advisable to use pluck

cust_ids = Branch.where(name: "New York").pluck(:customer_id)

MongoDB select where in array of _id?

Easy :)

db.collection.find( { _id : { $in : [1,2,3,4] } } );

taken from: https://www.mongodb.com/docs/manual/reference/operator/query/in/#mongodb-query-op.-in

How to join in mongo query with Array of IDs?

Try with below code.

const data = TESTModel.aggregate([
{
$lookup:{
from: "blogCategory",
localField: "CategoryID",
foreignField: "_id",
as: "enrollee_info"
}
}
])

Find with array of IDs in mongoose

You can use an $in operator and provide an array of IDs as is to the mongo. E.g. you can query the users that has specified IDs from the array:

const followedUsers = await User.find({ _id: { $in: followedIDs } });
console.log(followedUsers);

But, make sure that your followedIDs is an array of ObjectId. MongoDB stores _id as an ObjectId, not the string.

db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A" },
{ item: "notebook", qty: 50, status: "A" },
{ item: "paper", qty: 100, status: "D" },
{ item: "planner", qty: 75, status: "D" },
{ item: "postcard", qty: 45, status: "A" }
]);

db.inventory.find({ _id: { $in: [ObjectId("your_id_here")] } });

To generate such an array from the array of strings, use map:

const followedIDs = yourArrayWithIDAsString.map(ObjectId);


Related Topics



Leave a reply



Submit