valueOf() returns this:
[
{},
{ toUser: '5ed9d49c7e516616600eb693' },
{ toUser: '5ed9d49c7e516616600eb693' },
{ toUser: '5ed9d49c7e516616600eb693' },
{ toUser: '5ed9d3897e516616600eb692' }
]
I want to return only the value like "5ed9d3897e516616600eb692" or whatever toUser has. How?
This can be done in a couple of different ways, the best of which is using distinct :
db.collection.distinct("toUser")
Output will be:
[
'5ed9d49c7e516616600eb693',
'5ed9d49c7e516616600eb693',
'5ed9d49c7e516616600eb693',
'5ed9d3897e516616600eb692'
]
You can use reduce
and inside callback check if the object has any key using Object.keys
and length. If it has k then push the value using Object.values
into the accumulator array
let data = [{}, { toUser: '5ed9d49c7e516616600eb693' }, { toUser: '5ed9d49c7e516616600eb693' }, { toUser: '5ed9d49c7e516616600eb693' }, { toUser: '5ed9d3897e516616600eb692' } ]; let filterdValue = data.reduce((acc, curr) => { const objKey = Object.keys(curr); if (objKey.length > 0) { acc.push(...Object.values(curr)) } return acc; }, []); console.log(filterdValue)
You can use following query to convert object to string
> db.objectidToStringDemo.aggregate([{$project: {toUser: {$toString: "$toUser"}}}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.