Reputation: 182
I'm try to export my collections from mongodb with mongoose and Nodejs , using Modal.find();
to get all documents but it returns ids like {_id:"5ee8b4b32af76531cd46d714"}
but I need to this type {"_id":{"$oid":"5ee8b4b32af76531cd46d714"}
can you help me to get this type of id from Modal.find()
function?
{"_id":{"$oid":"5ee8b4b32af76531cd46d714"}
Upvotes: 2
Views: 1444
Reputation: 36114
You can use $literal to set $oid
,
$literal
is a aggregation pipeline operator, you can use this in find()
from MongoDB 4.4$arrayToObject
convert k and v format array of object to objectModal.find({},
{
_id: {
$arrayToObject: [
[
{
k: { $literal: "$oid" },
v: "$_id"
}
]
]
}
})
You can use this in aggregate() method, using $addFields / $set / $project operators.
Upvotes: 0
Reputation: 185
If I understand you, You just want to modify output of Model.find()
?
For that, you can use aggregate
instead of find
, and use $addFields
in aggregation.
So, query should look like this
model.aggregate([{$addFields: {_id: {"$oid": "$_id"}}}])
Problem with this query is that you can't actually use $
as first char of some field name, because it is reserved character for mongo operations, for example $addFields
So, proper query will be withoud $
in name of field
model.aggregate([{$addFields: {_id: {oid: "$_id"}}}])
But I think it is not a good practice to override default Document._id
, because it contains a bit more data than you expect.
For example, it contains timestamp when document was generated.
Upvotes: 1