We have this Schemes:
var SubsetSchema = new mongoose.Schema({
number: {
type: Number,
index: true,
unique: true,
},
name: String,
});
var RootSchema = new mongoose.Schema({
name: String,
subsets: [SubsetSchema],
});
mongoose.model('collection', RootSchema);
var Root = module.exports = mongoose.model('collection');
How would i perform search for a single Subset document across the whole collection where number = 3?
And i am not clear. In the case of schema above, would number be unique in the entire collection or per Root document?
You could use dot notation in the query and the $ positional operator in the projection to filter the output to just the matched subsets element like this:
Root.findOne({'subsets.number': 3}, {_id: 0, 'subsets.$': 1}, ...);
Regarding your second question, number would be enforced as unique across the entire collection, but (counter-intuitively) would still be allowed to exist multiple times in the same Root document.