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: 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] }
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
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
Rails Email Error - 530-5.5.1 Authentication Required
How to Run Ruby on Rails with Ruby 1.9X
How to Reference a File from Inside of a Gem
How to Debug Http of Ruby Google-Api-Client
Rails Model Name Conflict with Included Gem
Ruby 'Pg' Gem Linking to Wrong Copy of Libpq.5.Dylib (On Osx)
Export Content of a SQLite3 Table in CSV
How to Submit Polymorphic Comments on Feed? [Error]
Unknown Ruby Interpreter Version (Do Not Know How to Handle): Ruby_Version
M Hartl's Ruby on Rails Tutorial Chapter 5 Custom Title on Home Page
Heroku: Running Imagemagick with Paperclip
Generate Letters to Represent Number Using Ruby
How to Run Selenium (Used Through Capybara) at a Lower Speed
Partial Haml Templating in Ruby Without Rails
Puppet/Facter "Could Not Retrieve Fact Fqdn": How to Fix or Circumvent