mongodb java id 查询_mongodb在查询查询中将_id作为字符串

MongoDB 4.0添加了$convert聚合运算符和$toString别名,它允许您完全执行以下操作:

db.getCollection('example').aggregate([

{ "$match": { "example":1 } },

{ "$project": { "_id": { "$toString": "$_id" } } }

])

主要用法很可能是在文档中使用 _id 值作为"key" .

db.getCollection('example').insertOne({ "a": 1, "b": 2 })

db.getCollection('example').aggregate([

{ "$replaceRoot": {

"newRoot": {

"$arrayToObject": [

[{

"k": { "$toString": "$_id" },

"v": {

"$arrayToObject": {

"$filter": {

"input": { "$objectToArray": "$$ROOT" },

"cond": { "$ne": ["$$this.k", "_id"] }

}

}

}

}]

]

}

}}

])

哪个会回归:

{

"5b06973e7f859c325db150fd" : { "a" : 1, "b" : 2 }

}

这清楚地显示了字符串,另一个示例也是如此 .

通常,虽然通常有一种方法可以在光标上执行"transforms",因为文件是从服务器返回的 . 这通常是一件好事,因为 ObjectId 是一个12字节的二进制表示,而不是24字符的十六进制"string",这需要更多的空间 .

shell有一个 .map() 方法

db.getCollection('example').find().map(d => Object.assign(d, { _id: d._id.valueOf() }) )

NodeJS有一个 Cursor.map() ,可以做同样的事情:

let cursor = db.collection('example').find()

.map(( _id, ...d }) => ({ _id: _id.toString(), ...d }));

while ( await cursor.hasNext() ) {

let doc = cursor.next();

// do something

})

并且同样的方法也存在于其他驱动程序中(只是不是PHP),或者您可以只迭代光标并转换内容,这更可能是最好的事情 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值