如何删除mongodb中的多个文件?

时间:2017-05-04 16:58:10

标签: json mongodb

我有一个名为users的集合名称。在这个集合中,共有6个文件。我想使用名为“name”的列名之一删除3个文档。我使用了这个查询:

db.users.deleteMany([
{
"name":"viki"
},
{
"name" : "vino"
},
{
 "name" : "naranyamoorthy"
}
])

但我有错误,任何人都可以帮助我吗?

这些是我的文件。我想删除3个名为viki,vino,naranyamoorthy的文件。

 { "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123", "district" : [ "thambaram" ] } }
    { "_id" : ObjectId("58934f57e8796616482b48d1"), "name" : "vino", "age" : 21, "subject" : [ "Bootstrap", "j2ee", "java", null, "node" ], "address" : { "city" : "Antartica", "state" : "USA", "pincode" : "456", "country" : "USA", "core" : [ "alliswell" ] } }
    { "_id" : ObjectId("58934f8d09a2cb0d0c6f6af5"), "name" : "ranjith", "age" : 12, "subject" : [ "c++", "php", "java" ], "address" : { "city" : "japan", "state" : "UK", "pincode" : "45685" }, "subject[2]" : "php" }
    { "_id" : ObjectId("58955fd44b2ba9078463d2a7"), "name" : "waseem", "age" : 200, "subject" : [ "c++", "c", "Analysis" ], "address" : { "city" : "Dubai", "state" : "UAE", "pincode" : "5820", "country" : [ "USA" ] } }
    { "_id" : ObjectId("589561109b03d692c45114ef"), "name" : "sunadarpichai", "age" : 22, "subject" : [ "c", "node.js", "c++", "Android programming" ], "address" : { "city" : "losAngeles", "state" : "USA", "pincode" : "12341", "district" : "thambaram" } }
    { "_id" : ObjectId("58956389362992d7976510d4"), "name" : "naranyamoorthy", "age" : 21, "subject" : [ "Bootstrap", "node.js", "j2ee", "javascript" ], "address" : { "city" : "Afganistan", "state" : "tamilnadu", "pincode" : "9597653749", "country" : "USA", "core" : [ "alliswell" ] } }

3 个答案:

答案 0 :(得分:4)

您需要将单个查询对象传递给与您要删除的文档相匹配的deleteMany。在这种情况下,您可以使用$in

db.users.deleteMany({name: {$in: ["viki", "vino", "naranyamoorthy"]}})

答案 1 :(得分:0)

迭代删除文件的方式。

var deleteNames = ["viki","vino", "naranyamoorthy" ];
deleteNames.forEach(deleteDocument);
 function deleteDocument(item, index) {
  try {        
    db.collection.deleteMany({
        "name":item
    });  

  } catch (e) {
     print (e);
  }
}

答案 2 :(得分:0)

const products = await Product.find({
  category: "food"
}, {
  _id: 1
});

const productsIdForDeleting = products.map(function(product) {
  return product._id
})
console.log(productsIdForDeleting)
/*[
  5e7130675b9281305485b0b9,
  5e7130675b9281305485b0bf,
  5e7130675b9281305485b0ba
]*/

const deleteProductsResponse = await Product.deleteMany({
  _id: {
    $in: productsIdForDeleting
  }
});

console.log(deleteProductsResponse)


)