问题描述:

I have a few objects which I'd like to filter based on data of a nested object. Imagine that I have an object like this one:

{

"_id": ObjectId("57caf0aa229e53a68b2d2ac3"),

"name": "John",

"surname": "Lennon",

"contact": ObjectId("57caee695f4f1ba38b7badd3"),

"__v": 0

}

My goal is retrieving users with dial code +44. I tried to query like

User.find({"contact.dial_code":"+44"})

however it is returning 0 documents (and there should be a few of them). How do I do this query?

网友答案:

Ok so you can go this route using references to other collections, this results in smaller documents which may be easier to read, but your performance may take a hit.

It's usually better to embed the document... for instance:

{
  "_id": ObjectId("57caf0aa229e53a68b2d2ac3"),
  "name": "John",
  "surname": "Lennon",
  "contact": {
    "number": "(123)456-7890",
    "dial_code": "+44"
  },
  "__v": 0
}

Now your query will only be off of one collection.

If you insist on using references, you will have to do two queries and pass the results into a callback function via MongoDB Driver/Mongoose, or perhaps use the aggregation framework.

A mongoose call may look like...

Contact.findOne({dial_code: "+44"}, function(err, contacts) {
  // if no error and contacts.length > 0
  User.find({contact: "contacts._id"}, function(err, users) {
    // users is the array of users with dial_code "+44"
  });
});
网友答案:

In such case you can use $lookup (Official documentation) stage of aggregation pipeline to join two collections

Note: It Requires MongoDB 3.2

相关阅读:
Top