删除mongodb中ObjectId为_id字段类型的所有文档

删除mongodb中ObjectId为_id字段类型的所有文档,mongodb,mongodb-query,Mongodb,Mongodb Query,在我的集合中,我有几个文档,其中一些文档的\u id字段为字符串,另一些文档的类型为ObjectId {_id:"xxxx"} {_id:"yyyy"} {_id:"ObjectId(zzz)"} {_id:"ObjectId(xxxssssx)"} 我想删除_id字段类型ObjectId(这里是最后的文档) 有什么解决方法吗?要删除对象,您应该在下面的“新对象Id”中写入“仅删除给定对象Id的查询” db.collectioName.remove({"_id":new ObjectId("x

在我的集合中,我有几个文档,其中一些文档的
\u id
字段为字符串,另一些文档的类型为ObjectId

{_id:"xxxx"}
{_id:"yyyy"}
{_id:"ObjectId(zzz)"}
{_id:"ObjectId(xxxssssx)"}
我想删除_id字段类型ObjectId(这里是最后的文档)


有什么解决方法吗?

要删除对象,您应该在下面的“新对象Id”中写入“仅删除给定对象Id的查询”

db.collectioName.remove({"_id":new ObjectId("xxxssssx")})
或者干脆试试这个

db.collectioName.remove({"_id": ObjectId("xxxssssx")})

因为您无法更新id 您应该删除您的文档并再次插入它们,如下代码所示

db.test.find().forEach(function(item)
{
    if(typeof item._id == 'object')
    {                  
        var id = item._id.toString().replace('ObjectId(', '').replace(')', '');               
        db.test.remove({'_id': item._id});

        item._id = id;
        db.test.insert(item);
    }
});

您可以使用
$type
运算符。
对象Id的
类型是
7

 db.collection.remove({"_id":{$type:7}})

这将删除所有具有
\u id
字段的文档,这些字段表示为
对象id

如果您的文档具有
对象id
,则可以使用
$type

例如,如果您的收藏是

{
    "_id" : "foo"
}


{
    "_id" : "bar"
}


{
    "_id" : ObjectId("546c52074e418d78ff419897")
}


{
    "_id" : ObjectId("546c52074e418d78ff419898")
}
仅删除ObjectId

db.coll.remove({{u id:{$type:7}})

如果你的ObjectId是

{_id:"ObjectId(zzz)"}
{_id:"ObjectId(xxxssssx)"}
你能做到

db.coll.remove({“\u id”:{$regex:“^ObjectId”})

如果只想删除一个文档

db.coll.remove({“\u id”:{$regex:“^ObjectId”},{justOne:true})

显然,一个特定的_id

db.coll.remove({"_id" : "ObjectId(xxxssssx)"})

当我运行
db.coll.remove({u id:{$type:7}})
集合中的所有文档都被删除时,我有备份:)@iAmME with
db.coll.remove({u id:{$type:7})
只删除您写错的ObjectId。对于您的文档,不会删除任何内容,因为它们不是“真实的”
ObjectId
,而是
string
文档
{id:“xxxx”}{id:“yyyy”}{id:“ObjectId(zzz)”}{{id:“ObjectId(xxxssssx)”}
,不会删除任何内容。然后必须使用
$regex