Can Mongoid `any_of` include use of external document relationships?
I'开发者_开发技巧m using MongoDB with Mongoid and trying to put in place a rudimentary search as a placeholder before we look at weighting, etc. The any_of
method seems to be finding my embedded documents but not those linked by relations. Does anyone know if any_of
can include relationships to other documents in the db, and if so what the syntax would be?
belongs_to :principal #owner
belongs_to :account #owner
scope :search, ->(text) { any_of(
{:description => /#{text}/i},
{:name => /#{text}/i},
{"entries.title" => /#{text}/i},
{"entries.description" => /#{text}/i},
{:tags => /#{text}/i},
{"account.name" => /#{text}/i}, # Not finding by account name - because account isn't embedded?
{"principal.name" => /#{text}/i} # Not finding by principal name - because not embedded?
)}
No, any_of is the equivalent of a MongoDB $or query, so the native MongoDB would be something like:
db.collection.find(
{ "text" :
{ "$or" :
[ { "account.name" => /#{text}/i }, { "principal.name" => /#{text}/i } ]
}
})
Mongo queries only run over a single collection, so to resolve the account.name
and principal.name
fields they'd need to be embedded inside the document, e.g.
{
text:
{
description: "...",
name: "...",
account: { name: "..." },
principal: { name: "..." }
}
}
精彩评论