I am having these schemas:
//first
{
books: Number,
author: String
}
//second
{
book_id: ObjectId,
price: Number,
name: String
}
Now that any document has unique _id I want to take the _id from the first document and assign it to book_id from second document so I can find it later by:
db.collection.find({_id: user_id})
Do I have to use as a type of book_id : ObjectId and if I have to how should I continue ?
Related
I have a "log" type of collection, where depending on the source, there might be some id-fields. I want to search those fields with queries, but not sort by them. should I index them to improve search performance? To visualize the problem:
[{
_id: ObjectID("...") // unique
userId: ObjectID("...") // not unique
createdAt: ...
type: 'USER_CREATED'
},
{
_id: ObjectID("...") // unique
basketId: ObjectID("...") // not unique
createdAt: ...
type: 'BASKET_CREATED'
},
...]
I want to filter by (nullable) userId or basketId as well as the type-enum. I am not sure if those fields need an index. createdAT certainly does since it it is sortable. But sparse fields containing enums or null (and simply non-unique) values: how should those be treated as a rule of thumb?
I have Mongo document
{
"_id" : ObjectId("5e4c4c0935f4115dfc5540c2"),
"code" : "ABC"
}
and as per other SO threads looks like doing regex on Id is not possible as it has hexString. So I am querying with ObjectId
#Query("{'code': {$regex : ?0, $options: 'i'}, '_id': ?1}")
Page<Pack> findByCodeAndId(String code, ObjectId objectId, Pageable pageable);
now as the query paramets or optional, I have check if the passed id is valid before converting it to ObjectId
ObjectId objectId = null;
if (ObjectId.isValid(id)) {
objectId = new ObjectId(id);
}
now for the request {code: null, id: null} I want to bring first 10 documents as these are optional but the query is not working when it is passed null as ObjectId
Also tried ObjectId objectId = new ObjectId() but it is generating a random haxString and giving empty records when id is null
good day all,
need some help figuring out mongodb, mongoose and text search.
i have this as a schema
var itemSchema = new schema({
itemID: Number,
description: {type: Schema.Types.Mixed}
}
and in the collection in mongodb i have something like this
[
{
itemID:1
description: {
en: "car string in itemid 1"
fr: "voiture string in itemid 1"
es: "spanish string in itemid 1"
}
},
{
itemID:2
description: {
en: "motorcycle string in itemid 2"
fr: "motocyclette string in itemid 2"
es: "spanish string in itemid 2"
}
}
]
how do i do a text search like let's say i'm looking for "voiture" in description.
is the Schema.Types.Mixed appropriate for this kind of search or should it be changed. and how should i index such a field for better performance
thank you
You can only have one text index per collection, so rather than have an object with properties as strings I would suggest an array of objects that have the text and the language:
description: [
{ lang: "en", text: "car string in itemid 1" }
]
Then you could create an index like createIndex({ "description.lang": 1, "description.text": "text" }). Then query like query({ "description.lang": "fr", { $text: {$search: "voiture" } }). This assumes the language is known ahead of time which would be a more efficient query, but you could also create the index without the lang in which case all of the "description.text" properties would be searched.
I have the following schema:
var lessonSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
students: [{
_id: mongoose.Schema.Types.ObjectId,
attendance: {
type: Boolean,
default: false,
},
}],
});
The students array is an array of students who attended the particular lesson. I want to find a lesson using whether a particular user is present in the students array and then sent only that element of the students array which corresponds to the user making the request, along with all other fields as it is. For example, the query should return:
{
_id: 'objectid',
name: 'lesson-name'
students: [details of just the one student corresponding to req.user._id]
}
I tried using:
Lesson.find({'students._id': String(req.user._id)}, {"students.$": 1})
The query returns the document with just the id and the relevant element from the students array:
{
_id: 'objectid'
students: [details of the one student corresponding to req.user._id]
}
I tried using:
Lesson.find({'students._id': mongoose.Types.ObjectId(req.user._id)})
This returns the document with the details of all the students:
{
_id: 'objectid',
name: 'lesson-name'
students: [array containing details of all the students who attended the lesson]
}
How can I modify the query to return it the way I want?
You can return the name field by adding it to the projection object like this:
Lesson.find({ "students._id": String(req.user._id) }, { "name": 1, "students.$": 1 })
When you add a projection object (2nd parameter to find), the _id field is returned by default, plus whichever fields you set to 1.
Therefore, you were returning just the _id and the desired student but not the name field.
If you want to return all other fields and just limit the array to the matched item then you can make use of $slice in your projection:
Lesson.find({ "students._id": String(req.user._id) }, { "students.$": { $slice: 1 } })
I'm a new user of mongodb and I have a model like below. For update list data, I have to specify the element in an array. So I think I need to store a unique value for each element. Because list.name and list.price are variable data.
So are there any good ways to create an unique id in mongodb? Or should I create unique ids by myself?
{
name: 'AAA',
list: [
{name: 'HOGE', price: 10, id: 'XXXXXXXXXX'}, // way to add id
{name: 'FUGA', price: 12, id: 'YYYYYYYYYY'} // way to add id
]
}
Mongodb creates unique id only for documents. There is no better way for list or array elements. So, you should create Unique ids yourself.
Add keep in mind that, While updating your list use $addToSet.
For more information of $addToSet follow this documentation
use ObjectId() on your id field, so like..
db.test.update({name: "AAA"}, { $push: { list: {_id : ObjectId(), name: "dingles", price: 21} }});
reference: https://docs.mongodb.org/v3.0/reference/object-id/
whoever is seeing this in 2022, mongodb creates unique ids automatically we just have to provide schema for that particular array.
like,
_id : {
type: String
},
list: {
type: [{
Name : {
type: String
},
price : {
type: String
}
}]
}
this schema will generate auto id for all elements added into array
but below example will not create it.
_id : {
type: String
},
list: {
type: Array
}