My schema has an array of ObjectIds which are refs to another schema. What i want is to index this array entry using multikey indexing method of mongodb.
So that given an ObjectId of some document in the ProductCat Collection, i can list all the documents in my current collection which has the given ObjectId in the _pro_cat field.
I am confused about the exact way in which i should declare the field, in mongoose schema declaration, Here is what i am trying:
_pro_cat: { type: [mongoose.Schema.Types.ObjectId], ref: 'ProductCat', index: true }
_pro_cat: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ProductCat', index: true }]
The name of this collection is Seller. I am making the relation, by using the reference in the schema and the actual field value is an array, each of type ObjectId, which will be the ObjectIds of the documents in the other Collection (ProductCat in this case). If i index this field i.e.. _pro_cat, then given an ObjectId of a document in ProductCat Collection, i would be able to find all the documents in the Seller collection which has given ObjectId in its array field _pro_cat.
I think i may have to call a separate index function. But i thought that this is a field level indexing so it may not be needed.
I suspect the later is only for sub-docs and not for refs. Would greatly appreciate, if anyone could shed some light on it. Thanks.
Side Question: [RE-SOLVED]
In the mongodb documentation, it says that multikey indexing is automatic. multikey indexing. Does this mean that if that field is indexed, using the above methods, then mongo will recognize that the field is an array and use multikey indexing. OR does it mean that all the fields which are of array type will get indexed, without the need to explicitly telling it to index.
Thanks a lot.
related
Multikey Indexing means that every item in an array-field is indexed if you tell mongo to index the field.
It does not mean that all array fields are indexed automatically without the need to explicitely tell mongo to index the field.
Related
So currently when one of my documents is made, Mongo generates a random ObjectId. However I would like this to be a value of my choosing. I am using postman to test this and if I create a new document and specify a value for _id then it ignores it and overwrites it with the one that Mongo generates.
I am using node to define my schema and I haven't declared an _id field, is that what I must do?
Bydefault Mongodb will generate _id of Type ObjectId ,
in mongoose if you not define _id field , it will take _id of type ObjectId
if you want to add _id field by your self , you need to define like this in your mongoose model schema
_id: {
type: Number
}
I have a high-concurrency and parallelism situation and would like _id fields to be created by MongoDB and not by mongoose, so that I can use the ObjectId timestamps in the _id field to reliably query documents in the order they were inserted.
Is this possible? Right now I don't see how to do this with mongoose, as marking a schema with {_id: false} and trying to save it returns an error document must have an _id before saving.
Mongoose docs say the _id option only works on subdocuments, hence the error you get (http://mongoosejs.com/docs/guide.html#_id).
It might fit your situation to add a document without mongoose and in a subsequent operation update it through using mongoose (thereby keeping mongoose's Schema functionality etc).
I'm having trouble understanding with MongoDB is doing with my documents. I have a collection of a certain document. This document has a schema (I'm using Node.js Mongoose server-side). It has a couple of arrays of sub-documents. When I save a document that does not have an _id field Mongo should generate an _id field which it does. However, some of my 'sub-documents' also seem to have been given an _id field and other types of custom sub-documents were not. What the heck is going on here? Shouldn't I just get one _id per document?
I know there are no "joins" in MongoDB. I'm attempting to link a large number of documents to the 40,000+ locations in my locations collection.
My locations collection has custom (read: not under my control) identifiers for locations and their corresponding lat/lng coordinates.
var Locations = new Schema({
location_id: String,
loc: { //lng, lat: as per mongodb documents
type: [Number],
index: '2d'
}
});
There are several collections that have a field referencing this custom identifier to match latitude and longitude.
var MyCollection = new Schema({
location: String,
otherFields: Strings...
});
I'm a little lost on how to best go about this. A lot of posts suggest linking via Schema, but I've only seen that with an Schema.Types.ObjectId. This seems impractical for me because the data I'm importing only have the custom identifier.
Could I perhaps add another field into MyCollection and find the correct _id of the location to link to while I'm uploading data. If so, can someone point me in the right direction for accomplishing this.
Map reduce could be used somehow perhaps? I'm still a bit novice with Mongo.
Tried
I did try loading up the entirety of the location data into a JS object then checking that object against the return object from my other query, injecting the matching location data into my return object. This works but is unbearably slow.
First, just for the record: MongoDb will still generate an _id property for each object you store.
1. "[...], if the mongod receives a document to insert that does not contain an _id field, mongod will add the _id field that holds an ObjectId. [...]"
Source
You wrote that location_id is not under your control. And you want to use location_id because the other collections are using it also? So you don't want to break the standard in your project which is good.
As I see, you already have the location property in MyCollection and can store the location_id there.
As far as I know, you have to write your own linking methods now. You have to store the location_id in MyCollection and load the Location if you want to access if via MyCollection by
Locations.find({location_id: <the_location_id>})
But maybe your main problem is that you cannot find the Locations you are looking for in a reliable time?
I don't know your criteria for finding Locations for MyCollection is. If it is proximity of coordinates then you can reduce the amount of locations to check by filtering out the ones you really don't need to check. Then you don't have to check all the 40.000 Locations, but maybe just 100? In the following I assume it is the proximity.
Do you have lat, lon in both collections (Locations, MyCollection) ?
If so, you can define a query which gets locations around your MyCollection object (square). Then you will receive a smaller amount of Locations from MongoDb. Now you can apply your more complex check which checks if they really belong to your MyCollection-object.
something like this:
Locations.find({lat: {$gt: <x>-a, $lt: <x>+a}, lon: {$gt: <y>-b, $lt: <y>+b}}, function(locations){ ... });
I hope it helps.
I'm going nuts on a query to find a match based on referenced document properties.
I've defined my schema like this:
mongoose.model('Route', new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}));
mongoose.model('Match', new mongoose.Schema({
route: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Route'
}
}));
So when I'm searching for a route from a specific user in the Match model, I'd do something like (also tried without the '_id' property):
match.find({'route.user._id': '53a821577a24cbb86cd290d0'}, function(err, docs){});
But unfortunately it doesn't give me any results. I've also tried to populate the model:
match.find({'route.user._id': '53a821577a24cbb86cd290d0'}).populate('route').exec(function(err, docs){});
But this doesn't make a difference. The solutions I'm aware of (but don't think they're the neatest):
Querying all the results and iterate through them, filtering by code
Saving the nested documents as an array (so not a reference) inside the route model
Anyone suggestions? Many thanks in advance!
Related questions (but not a working solution offered):
Mongodb/Mongoose in Node.js. Finding by id of the nested document
Use mongoose to find by a nested documents properties
I'm going nuts on a query to find a match based on nested document properties
You don't have nested documents. You have references, which are just IDs that point to documents that reside in other collections. This is your basic disconnect. If you really had nested documents, your query would match.
You are encountering the "mongodb does not do joins" situation. Each MongoDB query can search the documents within one and only one collection. Your "match" model points to a route, and the route points to a user, but the match does not directly know about the user, so your schema does not support the query you want to do. You can search the "routes" collection first and use the result of that query to find the corresponding "match" document, or you can de-normalize your schema and store both the routeId and userId directly on the match document, in which case you could then use a single query.
Based on your question title, it seems like you want nested documents but you are defining them in mongoose as references instead of real nested schemas. Use full nested schemas and fix your data, then your queries should start matching.