要删除_id元素,可以使用以下语法-db.yourCollectionName.find({},{'_id': false}).pretty();
为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-> db.removingidElementDemo.insertOne({"UserName":"John",
... "UserAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9153fd4afe5c1d2279d6ad")
}
> db.removingidElementDemo.insertOne({"UserName":"Carol", "UserAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9154084afe5c1d2279d6ae")
}
> db.removingidElementDemo.insertOne({"UserName":"David", "UserAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9154154afe5c1d2279d6af")
}
> db.removingidElementDemo.insertOne({"UserName":"Mike", "UserAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9154204afe5c1d2279d6b0")
}
> db.removingidElementDemo.insertOne({"UserName":"Chris", "UserAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c91542c4afe5c1d2279d6b1")
}
在find()method的帮助下显示集合中的所有文档。查询如下-> db.removingidElementDemo.find().pretty();
以下是输出-{
"_id" : ObjectId("5c9153fd4afe5c1d2279d6ad"),
"UserName" : "John",
"UserAge" : 21
}
{
"_id" : ObjectId("5c9154084afe5c1d2279d6ae"),
"UserName" : "Carol",
"UserAge" : 24
}
{
"_id" : ObjectId("5c9154154afe5c1d2279d6af"),
"UserName" : "David",
"UserAge" : 22
}
{
"_id" : ObjectId("5c9154204afe5c1d2279d6b0"),
"UserName" : "Mike",
"UserAge" : 26
}
{
"_id" : ObjectId("5c91542c4afe5c1d2279d6b1"),
"UserName" : "Chris",
"UserAge" : 20
}
这是从PyMongo中删除_id元素的查询-> db.removingidElementDemo.find({},{'_id': false}).pretty();
以下是输出,在其中您无法看到_id元素,因为我们已将其删除-{ "UserName" : "John", "UserAge" : 21 }
{ "UserName" : "Carol", "UserAge" : 24 }
{ "UserName" : "David", "UserAge" : 22 }
{ "UserName" : "Mike", "UserAge" : 26 }
{ "UserName" : "Chris", "UserAge" : 20 }