here's my model:
class Person
acts_as_tree
end
i relate multiple objects as a tree:
P1
|
---
| |
P1.1 P1.2
|
---
| |
P1.1.1 P1.1.2
here if i need to retreive P1.1.1 i need to write a query that effectively asks:
get me the Person with name P1.1.1 and path (given by acts_as_tree) [P1, P1.1].
querying by just name is not enough as i can have similar named people at multiple paths.
how do i do this?
> db.people.find({name: 'P1.1.1'})
above snippet will show me the path attribute correctly as expected, but i cannot query by that path.
> db.people.find({name: 'P1.1.1',开发者_如何学JAVA path: [{name: 'P1'}, {name: 'P1.1'}]})
doesn't work. neither does:
> db.people.find({name: 'P1.1.1', path: [db.people.find({name: 'P1'}),
db.people.find({name: 'P1.1'})]})
but that explains what i'm trying to do.
One of the ways where you can query something like as follows:
db.people.find({name : 'Joe', 'path' : { $all : [ObjectId("4e0fcf1722b7a9439200002e"), ObjectId("4e0fcf1622b7a9439200002b")]}})
However the drawback I think of this is:
- You don't get to substitute the object relations/joins directly in mongo shell. You have to use the ObjectId object
- The $all clause does not necessitate that the order of path is strictly same, which means that a person with name "Joe" referenced by path "hometown/town/" would come up as well as "Joe" from "tome/hometown".
I would presume that second one may be a deal breaker. Also, I am presuming that mongoid in several cases pass across the query options directly to mongodb (or atleast there are ways to do that). Hence it should be possible to do a search in ruby code using given query above.
Nevertheless, I'll do some more re-search on this and post my findings back.
Hope it helps.
Edit
To alleviate the second problem above there is also another way to query a person with a specific path. Find it below:
db.people.find({name : 'Joe', 'path.0' :ObjectId("4e0fcf1722b7a9439200002e"), 'path.1':ObjectId("4e0fcf1622b7a9439200002b")})
This would ensure that path is exactly what you are looking for. However this works in mongodb shell and you may still need to figure out, how mongoid can run an equivalent of this. Plus you may have to construct this query dynamically to create a path for person and that (for deep nested people) may just become long and ugly.
I would suggest skimming through following links on mongodb documentation to get a better understanding.
http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray
I hope this is what you were looking for.
精彩评论