MongoDB将ObjectId从一个字段移动到另一个字段

时间:2019-04-27 03:21:20

标签: javascript database mongodb mongoose

问题

我有一个ObjectId保存在字段-incomingFriendRequests-中,我想将其移动到另一个字段-friends-。

是否有比将其从ReceivedFriendRequests中删除然后再执行findOneAndUpdate并将其添加到朋友更好的方法呢?我觉得这可以通过一个数据库调用而不是两个数据库调用来完成。

代码

猫鼬模型:

import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class Program4_v2 extends JFrame {   //extending Jframe for visual tree

    private static void write(LinkedBinaryTreeNode<String> root, String path){
        File file=new File(path);
        try (PrintWriter writer=new PrintWriter(file)){
            root.traversePreorder(node -> {
                if(node.getParent()==null){
                    writer.print(node.getData());
                }
                else{
                    writer.print("\n"+node.getData());
                }
            });
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }
    public static void add(BinaryTreeNode<String> oldNode, String data) {       //if statements helping to determine if there are more nodes


        BinaryTreeNode<String> newNode = new LinkedBinaryTreeNode<>(data); // failing line


        if (oldNode.hasLeftChild() && oldNode.getLeft().getData().contains("Q:")) {
            add(oldNode.getLeft(), data);
        } else if (oldNode.hasRightChild() && oldNode.hasLeftChild() && oldNode.getRight().getData().contains("Q")) {
            add(oldNode.getRight(), data);
        } else if (!oldNode.hasLeftChild() && oldNode.getData().contains("Q")) {
            oldNode.setLeft(newNode);
        } else if (!oldNode.hasRightChild() && oldNode.getData().contains("Q")) {
            oldNode.setRight(newNode);
        } else {
            boolean finished = false;
            BinaryTreeNode<String> node = oldNode.getParent();
            while (oldNode.getParent().getRight() != node) {
                if (node.getData().contains("A:")) {
                    node = node.getParent();
                } else if (!node.hasRightChild() && node.getData().contains("Q")) {
                    finished = true;
                    node.setRight(newNode);
                    break;
                } else if (node.getRight().getData().contains("A:") || node.getRight() == oldNode) {
                    node = node.getParent();
                } else {
                    finished = true;
                    add(node.getRight(), data);
                    break;
                }
            }
            if (!finished) {        //if there are more nodes, find them
                if (!node.hasRightChild()) {
                    node.setRight(newNode);
                } else {
                    add(node.getRight(), data);
                }
            }
        }
    }
    private static LinkedBinaryTreeNode<String>load(String path){


        LinkedBinaryTreeNode<String>root=new LinkedBinaryTreeNode<>(null); // failing line


        try {
            Scanner file = new Scanner(new File(path));
            String string = file.nextLine();


            root=new LinkedBinaryTreeNode<>(string); // failing line


            while(file.hasNext()){
                string=file.nextLine();
                add(root,string);
            }
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        return root;
    }
    private static String question(String question){
        System.out.println(question);
        Scanner scanner=new Scanner(System.in);
        String object=scanner.nextLine();
        if (object.contains("?")){
            return "Q:"+object;
        }
        else{
            return "A:"+object;
        }
    }
    private static void question(LinkedBinaryTreeNode<String>node){
        System.out.println(node.getData().substring(2));
        Scanner scanner=new Scanner(System.in);     //scanner in to along for computer to learn
        String string=scanner.next();
        if (string.contains("no")&& node.isLeaf()){
            String object= question("What was the correct answer?");        //printed text for when computer guesses wrong
            String question=question("What is the difference between "+node.getData().substring(2)+" and "+object.substring(2)+"?");
            String answer=question("What is the correct answer?");


            LinkedBinaryTreeNode<String>oldObject=new LinkedBinaryTreeNode<>(node.getData()); // failing line
            LinkedBinaryTreeNode<String>newObject=new LinkedBinaryTreeNode<>(object()); // failing line


            node.setData(question);
            if (answer.contains("yes")){
                node.setRight(newObject);
                node.setLeft(oldObject);
            }
            else{
                node.setRight(newObject);
                node.setLeft(oldObject);
            }
        }
        else if (string.contains("no")){
            question((LinkedBinaryTreeNode)node.getLeft());
        }
        else if (string.contains("yes")&& node.isLeaf()){       //you, or the computer, did it
            System.out.println("Excellent");
        }
        else{
            question((LinkedBinaryTreeNode)node.getRight());
        }
    }
    static JFrame frame;

    public static void main(String[] args) {
        System.out.println("20-Questions Game!");       //launching game
        LinkedBinaryTreeNode<String>root=load(args[0]);
        boolean play=true;
        while(play){
            System.out.println("Play?");        //asking to play
            Scanner scanner=new Scanner(System.in);
            if (scanner.next().equals("no")){       //you dont want to play! abort!
                play=false;
            }
            else{
                question(root);
            }
        }
        write(root,"20questions.data");     //writing game to new directory for future playing
        frame=new JFrame("20 Questions");
        JPanel panel=new TreeDisplayPanel(root);
        frame.add(panel);
        frame.setSize(1600,900);
        frame.show();
    }
}

What should be expected is a twenty-questions game that the program helps you make by sort-of playing. a GUI is also supposed to pop up but should work fine and seems unrelated to the problem

2 个答案:

答案 0 :(得分:0)

将值从一个字段移动到另一个字段肯定需要进行n +1次调用。可以使用

find({}).forEach(function(doc) {
  // your doc update
  doc.save();
});

或者您甚至可以执行批量写入。

如果您的目标是删除列incomingFriendRequests,则可以将列重命名为好友,而不是复制所有数据。

update({}, { $rename: {incomingFriendRequests: friends }});

答案 1 :(得分:0)

在单个查询中,您需要首先对传入的FriendRequests字段执行$ pull以删除所选的objectId,然后需要对好友执行另一个更新查询以添加所选的objectId,这是不可能的。另外,您可以使用$ addToSet来防止重复ID。如果在这种情况下使用$ push进行添加,则还会存储重复的objectId。

查询:-

1)删除:-db.getCollection('testdata')。update({id:ObjectId('5cc3fa66a04275096417f9ca')},{“ $ pull”:{“ incomingFriendRequests”:“ 5cc3fa66a04275096417f9da”}}})); < / p>

2)添加:- db.getCollection('testdata')。update({id:ObjectId('5cc3fa66a04275096417f9ca')},{“ $ addToSet”:{“ friends”:“ 5cc3fa66a04275096417f9da”}}));; //也可以使用$ push