MongoDB中多个位置标识符最经济的替代方案是什么?

MongoDB中多个位置标识符最经济的替代方案是什么?,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我有一个名为authors的集合,其架构如下: authors: { _id, firstName, lastName, posts: [ post 1: {...}, post 2: {...}, post 3: { _id, title, content, tags: [ tag 1: {...}, tag 2: {...}, tag 3: {

我有一个名为authors的集合,其架构如下:

authors: {
  _id,
  firstName,
  lastName,
  posts: [
    post 1: {...},
    post 2: {...},
    post 3: {
      _id,
      title,
      content,
      tags: [
        tag 1: {...},
        tag 2: {...},
        tag 3: {
          _id,
          name,
          description,
        },
      ],
    },
  ],
}
可以看到,posts是authors集合中的一个对象数组。该数组中的每个对象依次具有标记,即另一个对象数组。每个标记对象都有三个字段:_id、name和description

我正试图编写一个GraphQL变异来更新集合中匹配文档的这个名称字段

    const updatedTagInAuthor = await Author
  .updateMany({ 'posts.tags._id': args.newTagInfo._id },
    {
      $set: {
        'posts.$.tags.$.name': args.newTagInfo.name,
        'posts.$.tags.$.description': args.newTagInfo.description,
      },
    }, opts);
上述代码段显然失败了,因为MongoDB不允许在查询中使用多个位置元素$。那么,有没有经济的替代方案来完成我想做的事情呢

我尝试了MongoDB建议的ArrayFilter方法:

           const updatedTagInAuthor = await Author.update(
              {},
              { $set: { 'posts.$[].tags.$[tag].name': args.newTagInfo.name } },
              { arrayFilters: [{ 'tag._id': args.newTagInfo._id }], multi: true }
            );
但这会引发以下错误:

无法读取未定义的属性“castForQuery”

还是很困惑

试试这个

Author.update({"posts": { "$elemMatch": { "tags.id": args.newTagInfo._id } }}, 
    {'$set': {'posts.$[].tags.$.name': args.newTagInfo.name, 'posts.$[].tags.$.description': args.newTagInfo.description} }, 
    {multi: true});

这些是我正在用我给出的查询更新的文档

{"name" : "Steve","details" : [ {
        "work" : [ {
                "Company" : "Byjus",
                "id" : 1,
                "country" : "India"
            }, 
            {
                "Company" : "Vodafone",
                "id" : 2,
                "country" : "UK"
            }]
    }]},{"name" : "Virat","details" : [ {
        "work" : [ {
                "Company" : "Byjus",
                "id" : 1,
                "country" : "India"
            }, 
            {
                "Company" : "Verizon",
                "id" : 3,
                "country" : "US"
            }]
    }]}

QUERY:

db.getCollection('Users').update({"details": {"$elemMatch": {"work.id": 1}}}, {'$set': {'details.$[].work.$.Company': 'Boeing', 'details.$[].work.$.country': 'US'} }, {multi: true});
和你问的差不多,对吧?
尝试将这两个文档插入名为User的集合中,并直接在Mongo控制台中而不是在GUI中尝试上述查询。完全使用查询,而不仅仅是$set方法。

不会更新任何内容,但也不会引发任何错误。我已使用{$elemMatch:{tags.id:args.newTagInfo._id};在$elemMatch:{tags.id:1}之前更新了$elemMatch。可能就是这个错误。我已经注意到了这一点,并相应地修改了我的查询。但问题不在这一部分,因为我原来的.updateMany{'posts.tags.\u id':args.newTagInfo.\u id},还可以查找正确的文档。这是我无法使用的$set表达式。正如我所说,您的解决方案不会抛出错误,但也不会更新集合中的任何内容。您使用的是Mongo DB的哪个版本?我使用Mongo 4进行了此操作,如果您使用的是Mongo DB 4,请在Mongo控制台中尝试此代码。是否使用Mongo运行版本4.0.6的Atlas。